Using if structure we can test one condition and execute statements inside if.
But sometime if condition of if structure is false then other set of statements has to be execute.
OR you want to execute a statement if a certain condition is met, and a different statements if the condition is not met.
This is done by using else structure.
else extends an if statement, if condition of if is false.
Syntax of else
Following is a general syntax of else:
1 2 3 4 5 6 7 8 |
if(expression) { // statements } else { //statements } |
Flowchart of else
Example of if-else –
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $a = 10; $b = 5; if($a < $b) { echo "a is bigger than b"; } else { echo "b is bigger than a"; } ?> |
output:
1 |
b is bigger than a |
The else statement is only executed if the if expression evaluated to FALSE.
Firstly the if condition is checked, if it is false then else body is execute.