WHAT IS CONDITIONAL STATEMENT IN PHP?
Conditional Statements are used when you need to make decision pragmatically. If Else and Switch Case are the main Conditional Statement in PHP that executes certain block of codes based on matched condition. For Example,
You have a list of Items for Male and Female and you want to show the only item based on gender.
HOW MANY TYPES OF CONDITIONAL STATEMENTS ARE THERE IN PHP?
You can use following decision-making keyword in PHP.if Statementif else Statementif elseif else Statementswitch case statement
IF STATEMENT
It executes a block of codes if condition matched.
Example
<?php
$x=5;
$y=10;
if($x!=$y)
{
echo $x." is not equal to ".$y;
}
?>
Output
IF ELSE STATEMENT
There is two blocks of codes in IF Else statement. If condition matches then IF block gets executed otherwise Else block gets executed.
<?php
$x=5;
$y=10;
if($x==$y)
{
echo $x." is equal to ".$y;
}
else
{
echo $x." is not equal to ".$y;
}
?>
Output
IF ELSEIF ELSE STATEMENT
If there are multiple conditions to be tested then If ElseIF Else statement is used.
<?php
$x=5;
$y=10;
if($x == $y)
{
echo $x." is equal to ".$y;
}
elseif($x > $y)
{
echo $x." is greater than ".$y;
}
elseif($y % 2 == 0)
{
echo $y." is an even number";
}
else
{
echo $x." is not equal to ".$y;
}
?>
Output
SWITCH CASE STATEMENTS
If there are multiple conditions then Switch Case is the best way to test them.
<?php
$day="Sunday";
switch($day)
{
case "Monday":
echo "This is Monday";
break;
case "Wednesday":
echo "This is Wednesday";
break;
case "Friday":
echo "This is Friday";
break;
case "Sunday":
echo "This is Sunday";
break;
default:
echo "Days not found";
}
?>
Output
SUMMARY
In this chapter, you learned PHP Condition Statement like If Else and Switch Case with programming example. The examples are very basic and our motive is to teach you conditional statement with easy programming example. In the next chapter, you will learn Loops in PHP.