if, elseif and else
An if runs its block when the condition is truthy. Add any number of elseif branches and an optional else; PHP checks them top to bottom and runs only the first branch whose condition is true. The condition goes in parentheses, the block in braces. Braces are optional for a single statement, but every coding standard requires them — leaving them out is how "I added a line and it always runs" bugs happen.
<?php
declare(strict_types=1);
function grade(int $score): string
{
if ($score >= 90) {
return "A";
} elseif ($score >= 75) {
return "B";
} elseif ($score >= 50) {
return "C";
} else {
return "F";
}
}
echo grade(95), " ", grade(80), " ", grade(50), " ", grade(12), "\n";
$cart = [];
if (!$cart) { // an empty array is falsy
echo "Your cart is empty\n";
}
$age = 17;
$hasTicket = true;
if ($age >= 18 && $hasTicket) {
echo "Enter\n";
} elseif ($age < 18 && $hasTicket) {
echo "Enter with an adult\n";
}A B C F
Your cart is empty
Enter with an adultAdd an "A+" grade for scores of 98 and above. Where must that branch go in the chain, and why?
elseif and else if behave the same (the second is an else containing an if). PSR-12 prefers elseif, and it is the only one that works with the colon syntax at the end of this module.return (or continue in a loop), so the main path stays at the left margin: if ($user === null) { return; }. Three levels of nested if is a code-review smell in any language.Parse error: Unclosed '{'
<?php
$temp = 30;
if ($temp > 25) {
echo "hot\n";
} elseif ($temp > 15) {
echo "warm\n";Parse error: Unclosed '{' on line 5 in main.php on line 6The elseif block opened on line 5 is never closed. PHP only notices at the end of the file (line 6), so the message gives you both numbers: where the brace was opened and where PHP gave up. Go to the first line number.
Close every brace you open. Editors highlight matching pairs; a formatter re-indents the file so a missing brace shows up as wrong indentation.
<?php
$temp = 30;
if ($temp > 25) {
echo "hot\n";
} elseif ($temp > 15) {
echo "warm\n";
}