This tutorial teaches you how to write decision-making code using if...else...elseif statements in PHP.
You can use PHP Conditional statements to write code if you want to perform different actions for different conditions.
While writing programs, there will be situations when you want to execute a particular statement only if some condition is satisfied. In such cases, you use conditional statements.
In PHP, the conditional statements are of four types. These are:
If statements are used when you want to execute some code when a condition is true.
Syntax:
if(condition) {
// code to be executed if 'condition' is true
}
Check the example
<?php
$age = 18;
if($age <= 25)
{
echo "You are not allowed to ride the bike";
}
?>
Output:
You are not allowed to ride the bike
The if...else statements are used when you want to execute some code when a condition is true and a different code when that condition is false.
Syntax:
if(condition) {
// code to be executed if 'condition' is true
} else {
// code to be executed if 'condition' is false
}
Example
<?php
$age = 19;
if($age <= 18)
{
echo "You are not allowed to ride the bike";
}
else
{
echo "Enjoy the ride";
}
?>
Output:
Enjoy the ride
The if...elseif...else statements are used when you want to execute different code for a different set of conditions and have more than two possible conditions.
Syntax
if(condition1) {
// code to be executed if 'condition1' is true
} elseif(condition2) {
// code to be executed if 'condition2' is true
} else {
/* code to be executed if both 'condition1' and 'condition2' are false */
}
Example
<?php
// speed in kmph
$speed = 110;
if($speed < 60)
{
echo "Safe driving speed";
}
elseif($speed > 60 && $speed < 100)
{
echo "You are burning extra fuel";
}
else
{
// when speed is greater than 100
echo "Its dangerous";
}
?>
Output:
Its dangerous
In the example mentioned above, logical operators && have been used. Logical operators are very helpful in writing multiple conditions together.