The if
statement in PHP is used to execute a block of code if a certain condition is true. The else
statement is used to execute a block of code if the condition is false. Here is an example of how to use the if
and else
statements in PHP:
$x = 10;
if ($x > 5) {
echo "x is greater than 5";
} else {
echo "x is not greater than 5";
}
In this example, the condition is $x > 5
, which evaluates to true. Therefore, the code inside the first block (echo "x is greater than 5"
) will be executed. If the condition were false, the code inside the else
block (echo "x is not greater than 5"
) would be executed instead.
You can also use the elseif
statement to check for multiple conditions. For example:
$x = 10;
if ($x > 15) {
echo "x is greater than 15";
} elseif ($x > 10) {
echo "x is greater than 10 but not greater than 15";
} else {
echo "x is not greater than 10";
}
In this example, the first condition ($x > 15
) is false, so the code moves on to the elseif
condition ($x > 10
). Since this condition is true, the code inside the elseif
block (echo "x is greater than 10 but not greater than 15"
) is executed. If neither the if
nor the elseif
conditions were true, the code inside the else
block (echo "x is not greater than 10"
) would be executed.