PHP Conditional(Branching) Statements
We can use branching statements in our code to make decisions. PHP supports following decision making statements:-
- if statement
- if...else statement
- if...elseif...else statement
- switch statement
if Statement
The if statement executes a code if the condition returns true.
Syntax:
if (condition/conditions)
{
execute the code
}
Eg:
<?php
$x = 20; $y = 5;
if($x > $y)
{
echo "X greater than Y";
}
?>
if…else Statement
It executes a code if a condition is true and another code if the condition is false.
Syntax:
if (condition)
{
execute the code - condition is true
}
else
{
execute the code - condition is false
}
Eg:
<?php
$x = 5; $y = 20;
if($x >= $y)
{
echo "X greater than or equal to Y";
}
else
{
echo "X less than Y"; // this code is executed
}
?>
if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.
Syntax:
if (condition)
{
execute the code - if condition is true
}
elseif(condition)
{
execute the code - this condition is true
}
else
{
execute the code - conditions are false
}
Eg:
<?php
$x = 20; $y = 20;
if($x > $y)
{
echo "X greater than Y";
}
elseif($x == $y)
{
echo "X equals Y"; // this code is executed
}
else
{
echo "X less than Y";
}
?>
switch Statement
Switch selects one of many blocks of code to be executed. The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax:
switch (n)
{
case 1:
code to be executed if n=1;
break;
case 2:
code to be executed if n=2;
break;
case 3:
code to be executed if n=3;
break;
...
default:
code to be executed if n is different from all case labels;
}
The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.
Eg:
<?php
$fruit = "apple";
switch ($fruit)
{
case "orange":
echo "Your fruit is orange!";
break;
case "apple":
echo "Your fruit is apple!"; // this will be shown in output
break;
case "banana":
echo "Your fruit is banana!";
break;
default:
echo "Your fruit is not orange, apple or banana!";
}
?>
If break is not used, all the statements will execute after finding a matched case.