if runs code when a condition is true. Add else to run something different when it is false.
<?php
$age = 15;
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
Minor
Exactly one of the two blocks runs, never both and never neither.
A real example: login state
<?php
$isLoggedIn = false;
if ($isLoggedIn) {
echo "<a href='/logout'>Log out</a>";
} else {
echo "<a href='/login'>Log in</a>";
}
<a href='/login'>Log in</a>
A discount rule
<?php
$cartTotal = 450;
if ($cartTotal >= 500) {
$shipping = 0;
} else {
$shipping = 49;
}
echo "Shipping: $shipping";
Shipping: 49
The early return pattern
Inside a function, you can often skip else by returning early. The code becomes flatter and easier to read.
<?php
function describeAge(int $age): string
{
if ($age < 0) {
return "Invalid age";
}
if ($age >= 18) {
return "Adult";
}
return "Minor";
}
echo describeAge(20) . "\n";
echo describeAge(-5);
Adult
Invalid age
Compare that with one deep if ... else if ... else chain. The early return version has no extra nesting.
else needs an if
else cannot stand alone. It always belongs to the if directly above it.
Handle the unusual case first
return. The main logic then runs without extra nesting.