MENU
Conditionals
A conditional statement can be specified by if:if (condition1) {statements1;}
elseif (condition2) {statements2;}
elseif……
else {statements3;}
If condition1 evaluates to true, statements1 will be executed. Otherwise condition2 will be checked, and so on. If all the conditions are false, statements3 will be executed. The elseif and else clauses are optional, and there may be any number of elseif clauses.
If the expression that is compared needs to be evaluated only once, switch may be used instead.
switch(expression){
case value1: statements1; break;
case value2: statements2; break;
case value3: statements3; break;
……
default: statements4;
}
On the other hand, the ternary operators ?: allow a value to be chosen among multiple values within an expression.
Note: Syntactically PHP allows a second form for if, while, for, foreach, and switch. ‘{‘ is changed to ‘:’ and ‘}’ to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
The following three code segments are similar:
The following three code segments are similar
If break; is omitted at the end of a case clause in the switch statement, PHP will go on running the statements in the next case.
match is a more concise alternative to switch. It compares strictly (like ===), never falls through from one arm to the next, and is itself an expression – it evaluates to a value that can be returned, assigned, or passed along.
if ($a+$b==2): $x="two";
elseif ($a+$b==1): $x="one";
else : $x="zero";
endif;switch ($a+$b){
case 2: $x="two"; break;
case 1: $x="one"; break;
default: $x="zero";
}$x = ($a+$b==2)?"two"
: ($a+$b==1)?"one"
:"zero";A single arm can list several comma-separated conditions, and default catches everything else. The whole expression's result is assigned directly to $label.
Unlike switch, which compares loosely (like ==), match compares strictly. The string "1" does not match the integer arm 1:
<?php
$status = 2;
$label = match ($status) {
0 => "Pending",
1 => "Active",
2, 3 => "Closed",
default => "Unknown",
};
echo $label . "\n";
?>Closed
<?php
$value = "1";
$result = match ($value) {
1 => "matched the integer 1",
"1" => "matched the string '1'",
default => "no match",
};
echo $result . "\n";
?>matched the string '1'
<?php
$status = 9;
try {
$label = match ($status) {
0 => "Pending",
1 => "Active",
};
} catch (\UnhandledMatchError $e) {
echo "Caught: " . $e->getMessage() . "\n";
}
?>Caught: Unhandled match case 9
<?php
function gradeLabel(int $score): string {
return match (true) {
$score >= 90 => "A",
$score >= 80 => "B",
$score >= 70 => "C",
default => "F",
};
}
echo gradeLabel(95) . "\n";
echo gradeLabel(82) . "\n";
echo gradeLabel(50) . "\n";
?>A
B
F