PHP If Else and Match
PHP if else statements let your program make decisions. You test a condition, and PHP runs a block of code only when that condition is true. PHP 8 also adds the match expression, a cleaner alternative to switch.
If, Elseif and Else
PHP checks each condition from top to bottom and runs only the first block that matches.
<?php
$score = 72;
if ($score >= 80) {
echo "Grade A";
} elseif ($score >= 60) {
echo "Grade B";
} else {
echo "Try again";
}Grade B
Combining Conditions
<?php
$age = 25;
$hasTicket = true;
if ($age >= 18 && $hasTicket) {
echo "Welcome in\n";
}
if (!$hasTicket || $age < 18) {
echo "Access denied";
} else {
echo "Enjoy the show";
}Welcome in Enjoy the show
The Switch Statement
switch compares one value against many cases. Do not forget break, or PHP keeps running the following cases (fall-through). switch uses loose comparison (==).
<?php
$day = "sat";
switch ($day) {
case "sat":
case "sun":
echo "Weekend";
break;
default:
echo "Weekday";
}Weekend
The PHP Match Expression
match returns a value, uses strict comparison (===), needs no break, and throws an UnhandledMatchError if nothing matches and there is no default. For most new code it is the better choice.
<?php
$status = 404;
$message = match ($status) {
200, 201 => 'Success',
404 => 'Not found',
500 => 'Server error',
default => 'Unknown',
};
echo $message;Not found
Match With Conditions
Use match(true) to test ranges in a compact way.
<?php
$temp = 31;
echo match (true) {
$temp < 10 => 'Cold',
$temp < 25 => 'Mild',
default => 'Hot',
};Hot
Alternative Syntax in Templates
Inside HTML templates, PHP offers a colon syntax that is easier to read: if (...): ... elseif (...): ... else: ... endif;. The same exists for foreach and while.
Frequently asked questions
What is the difference between match and switch in PHP?
match is an expression that returns a value, uses strict === comparison and needs no break. switch is a statement with loose comparison and fall-through.
Is it elseif or else if in PHP?
Both work with curly braces. With the colon alternative syntax only elseif is valid, so elseif is the common style.
Can I use match without a default?
Yes, but if no arm matches PHP throws an UnhandledMatchError, so add default unless every possible value is covered.