The if...else
statement executes one block of code if a condition is true and another block if the condition is false.
Syntax
if (condition) { // Code executed if the condition is true } else { // Code executed if the condition is false }
Example
Here’s an example based on motorcycles. If you own fewer than 5 motorcycles, it suggests buying a Yamaha; otherwise, it suggests riding a Honda:
$motorcycleCount = 3; // Change this number to test different outputs if ($motorcycleCount < 5) { echo "Why not add a Yamaha to your collection?"; } else { echo "Take your Honda for a spin!"; }
PHP – The if…elseif…else Statement
The if...elseif...else
statement allows you to evaluate multiple conditions and execute different blocks of code accordingly.
Syntax
if (condition) { // Code executed if this condition is true } elseif (condition) { // Code executed if the first condition is false and this one is true } else { // Code executed if all conditions are false }
Example
Consider this example based on cars. If someone has fewer than 2 cars, it suggests a Tesla; if they own between 2 and 5, it suggests a Toyota; otherwise, it recommends driving a BMW:
$carCount = 4; // Change this number to test different outputs if ($carCount < 2) { echo "Maybe consider buying a Tesla."; } elseif ($carCount <= 5) { echo "How about getting a reliable Toyota?"; } else { echo "Enjoy your luxurious BMW!"; }