The if and else statements in PHP are control structures that allow you to execute different blocks of code based on conditions. They are fundamental for decision-making in your PHP scripts.
if StatementThe if statement checks a condition, and if it's true, it executes the block of code inside:
<?php
$number = 10;
if ($number > 5) {
echo "The number is greater than 5.";
}
?>Output:
The number is greater than 5.else for Alternate ConditionsThe else statement runs a block of code when the if condition is false:
<?php
$number = 3;
if ($number > 5) {
echo "The number is greater than 5.";
} else {
echo "The number is not greater than 5.";
}
?>Output:
The number is not greater than 5.elseif for Multiple ConditionsYou can use elseif (short for "else if") to check additional conditions:
<?php
$number = 8;
if ($number > 10) {
echo "The number is greater than 10.";
} elseif ($number > 5) {
echo "The number is greater than 5 but not greater than 10.";
} else {
echo "The number is 5 or less.";
}
?>Output:
The number is greater than 5 but not greater than 10.if StatementsYou can nest if statements to check complex conditions:
<?php
$x = 7;
$y = 15;
if ($x > 5) {
if ($y > 10) {
echo "x is greater than 5 and y is greater than 10.";
}
}
?>Output:
x is greater than 5 and y is greater than 10.Combine conditions with logical operators like and, or, and !:
<?php
$age = 20;
if ($age >= 18 && $age <= 25) {
echo "You are eligible for this program.";
}
?>Output:
You are eligible for this program.Practice creating decision-making structures in PHP. Understanding if, else, and elseif will help you build dynamic and interactive web applications. Now you can learn about loops!