In PHP If else is a control structure and it is the heart topic of PHP Scripts. It will be used whenever you have performed the conditional statements.
If
PHP if statement executes the block of code when the expression evaluates to TRUE
Syntax:
1 2 |
if(expression) code |
Example
1 2 3 4 5 6 7 |
<?php $a = 5; $b = 7; if($a < $b) echo 'b is greater than a'; ?> |
Inside HTML / Javascript or CSS, we can write if statement like below:
1 2 3 4 5 6 7 |
<?php $a = 5; $b = 7; if($a < $b): ?> <p>b is greater than a</p> <?php endif;?> |
We can write if statements within another if statements infinitely.
Syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
if(expression) { php code -- -- if(expression) { php code -- -- if(expression) { php code -- -- } } } |
else
Whenever the expression in if statement evaluates to FALSE and it constructed with else statement and then the “else” block will be executed.
Syntax:
1 2 3 4 |
if(expression) code else code |
Example
1 2 3 4 5 6 7 8 |
<?php $a = 5; $b = 7; if($a < $b) echo 'b is greater than a'; else echo 'a is greater than b'; ?> |
Like if statement, else statement also can be nested infinitely.
else if
We can understand with the name itself. If we combine both else and if statements together, it is called as “elseif” or “else if” statement.
There should be else block after elseif block, if else part is missing after elseif block then PHP throws fatal error.
Syntax:
1 2 3 4 5 6 |
if(expression) code elseif code else code |
Consider the following example, there we have used all the if, else and else if concepts together.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $a = rand(1,3); if($a == 1) { echo 'a = '.$a.'. The random value is one'; } else if($a == 2) { echo 'a = '.$a.'. The random value is two'; } else { echo 'a = '.$a.'. The random value is three'; } ?> |
We will discuss later about the rand() function.
Click the below button to see the demo.
Demo