if and else
The if statement
if runs its block only when the condition holds. Anything that becomes true or false works as a condition:
$score = 75;
if ($score >= 60) {
echo "Passed!";
}
elseif chains
elseif adds more branches, else catches everything left. Only the first matching branch runs:
$score = 85;
if ($score >= 90) {
echo "Excellent";
} elseif ($score >= 60) {
echo "Passed";
} else {
echo "Failed";
}
Nesting vs early return
Nested branches pile indentation and hide the main path. Returning early keeps the happy path flat:
function label(int $score): string
{
if ($score < 60) {
return "Failed";
}
return "Passed";
}
Guard clauses
Guard clauses push every rejection to the top of the function. What remains below is the real work, free of else blocks:
function admit(?string $name, int $age): string
{
if ($name === null) {
return "No name given";
}
if ($age < 18) {
return "Too young";
}
return "Welcome, " . $name . "!";
}
Next: switch and match
Автор статьи: Arthur Isaev