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 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 –
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.
a is less than 20
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.
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.
a is less than 20
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.
In the above example, both the conditions are FALSE, therefore the code in the else block is executed.
a is less than 10
The Switch statement is explained in next lesson.