PHP, if else allows to execute or run code on the basis of conditions. PHP provides various control structure
- if
- if else
- if else if
- switch
if
if checks the given condition, and returns true or false. If true then executes statements inside if block. It is also called “Simple if”
Syntax
if(condition)
{
// set of statements
}
Example
<?php
$a = 20
if($a <= 20)
{
echo "if block executed";
}
?>
if-else
if condition only executes code when it returns true, what if, condition fails and returns false, In such condition else is used to execute the statement.
Syntax
if(condition)
{
// set of statements
}
else
{
// set of statements
}
Example
<?php
$a = 20
if($a > 20)
{
echo "else block executed";
}
?>
if else if else
To check multiple conditions, if else if is used. With if-else there is limitation. you can check condition only one time, So if else if else allows to check different conditions, and whichever condition is true, the related statements get executed.
Syntax
if(condition)
{
// set of statements
}
else if(condition)
{
// set of statements
}
else if(condition)
{
// set of statements
}
else
{
// set of statements
}
Example
<?php
$a = 20
if($a < 20)
{
echo "if block executed";
}
else if($a > 20)
{
echo "else if block executed";
}
else
{
echo "else block executed";
}
?>
- There is no limit in using else-if.
- else if always comes after if.
- else is optional and always comes after else if block.
- When if and all else if condition fails, else block executes.
In if else if or else curly braces {} are used for multiple statements, for single statement curly braces are not mandatory.
<?php
$a = 20;
if($a < 20)
echo "a is less than 20";
else{
echo "Multiple statement ";
echo "curly {} braces are mandatory";
}
?>