PHP uses conditional statements to perform different actions based on different conditions. The main conditional statements in PHP are if, else, and elseif.
The general syntax for these statements is:
if (condition) {
// code to be executed if condition is true
} elseif (condition) {
// code to be executed if the first condition is false and this condition is true
} else {
// code to be executed if all conditions are false
}
The following example demonstrates the use of if, else, and elseif statements:
<?php
$var = 20;
if ($var > 25) {
echo "The value is greater than 25.<br>";
} elseif ($var == 20) {
echo "The value is equal to 20.<br>";
} else {
echo "The value is less than 20.<br>";
}
?>
The value is equal to 20.
This example shows how PHP checks conditions in sequence. The first condition checks if the variable `$var` is greater than 25. If false, it checks if `$var` is equal to 20, and since this is true, the corresponding message is displayed.
The following example demonstrates a nested if-else structure:
<?php
$var1 = 10;
$var2 = 5;
if ($var1 > $var2) {
if ($var1 == 10) {
echo "\$var1 is 10 and greater than \$var2.<br>";
} else {
echo "\$var1 is greater than \$var2 but not 10.<br>";
}
} else {
echo "\$var1 is less than or equal to \$var2.<br>";
}
?>
$var1 is 10 and greater than $var2.
PHP's if, else, and elseif statements are essential tools for controlling the flow of your program. Understanding how to use them efficiently can help you create more dynamic and responsive PHP scripts.