The if-else statement is used in PHP to perform conditional operations. It helps in making decisions in your code. Based on the given condition, it either executes the code block inside the `if` statement or the `else` block.
<?php if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is false } ?>
In the basic structure:
<?php $x = 10; if ($x > 5) { echo "x is greater than 5"; } else { echo "x is not greater than 5"; } ?>
In this example:
$x
is greater than 5. Since $x
is 10, the result will be: "x is greater than 5".If you need more than two conditions, use else-if to check multiple conditions in a chain. This helps when you have more than two possible outcomes.
<?php $x = 15; if ($x > 20) { echo "x is greater than 20"; } elseif ($x == 15) { echo "x is equal to 15"; } else { echo "x is less than or equal to 10"; } ?>
Here:
$x
is greater than 20, which it isn't. Then, it checks if $x
is equal to 15, which is true, so it prints: "x is equal to 15".You can also combine multiple conditions in an if-else statement using logical operators like AND (&&
) and OR (||
).
<?php $x = 10; $y = 20; if ($x == 10 && $y == 20) { echo "Both conditions are true."; } elseif ($x == 10 || $y == 25) { echo "One condition is true."; } else { echo "Neither condition is true."; } ?>
In this example:
&&
(AND) operator ensures both conditions must be true to execute the first block.||
(OR) operator checks if at least one condition is true.Sometimes, you need to check multiple conditions within each other. This is called nesting if-else statements.
<?php $x = 10; if ($x > 5) { if ($x < 15) { echo "x is greater than 5 and less than 15."; } else { echo "x is greater than 15."; } } else { echo "x is 5 or less."; } ?>
In this example:
$x
is greater than 5 first. Then, inside that condition, we check if $x
is less than 15.&&
and OR ||
) can be used to combine conditions.Now you're ready to make decisions in your PHP programs using if-else statements! 🎉
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!