If Statement | PHP Tutorial

Conditional statements in PHP, like any other programming language helps us to perform actions based on some type of conditions. These conditions can be logical or comparative.

Conditions are checked, whether they are TRUE or FALSE, and then an action is performed.

In PHP there are mainly 4 conditional statements

– if statement

– if…..else statement

– if……elseif……else statement

– switch statement

if condition

If conditions has one-way path and that is executed only when the condition turns out to be TRUE –

The if block can contain a single statement or a set of statements that needs to be executed when condition is valid or TRUE –

Syntax

Example

In the above example we’ve declared a variable name $a and set it’s value to 10. Then we used a condition to check if a is less than 20, that is TRUE, so it’ll print ‘a is less than 20’.

In the second condition we are checking if $a is greater than 20, which is FALSE, therefore the following statement will not work.

Output

a is less than 20

if….else statement

If else statement is an enhancement in if condition. It has two way path both for TRUE and FALSE condition –

If the condition turn out to be TRUE, the if block is executed, otherwise, the else block is executed.

Syntax

Example

In the above example, the condition is checking whether $a is greater than 20 or not. Since condition is FALSE, the statement block in else part is executed.

Output

a is less than 20

if……elseif….else statement

Both of the above statements, check for only one condition, but what there are multiple conditions that needs to be checked – the if….elseif….else statement can be used.

The else block is executed when all the statements comes out to be FALSE.

Syntax

Example

In the above example, both the conditions are FALSE, therefore the code in the else block is executed.

Output

a is less than 10

Switch Statement

The Switch statement is explained in next lesson.

Author: Deepak Kumar

This is Deepak Kumar, founder of True Infosystems and of-course the chief content creator at CodingLessions.info. Started my carrier as a Freelancer and now a top-rated Freelancer at Upwork, delivered over 200 successful projects with highly positive user ratings and counting.