This program implements the same logical tests with if and then with match. We can see clearly how the 2 styles of code look when making the same checks.
Version 1 We test the size variable with if, elseif and else. If the size if 10, we set result to "Ten".
Version 2 We use match to check the size variable for 2 values—20 and 10. This gives us the value "Ten" again.
$size = 10;
// Version 1: use if and elseif for testing.
$result = 0;
if ($size == 20) {
$result = "Twenty";
} elseif ($size == 10) {
$result = "Ten";
} else {
$result = "?";
}
echo "Size is " . $result . "\n";
// Version 2: use match for testing.
$result = match ($size) {
20 => "Twenty",
10 => "Ten",
};
echo "Size is " . $result . "\n";Size is Ten
Size is Ten
Nested if. It is sometimes necessary to nest if-statements, and this is supported. But if we can collapse nested blocks, and use a logical AND operator, this may make code clearer.
Version 1 We test the code variable for 5, and the animal variable for "bird". If both tests succeed, we print a message.
Version 2 We make both tests, the same as in the first version, but we combine them onto one line with a logical AND.
$code = 5;
$animal = "bird";
// Version 1: use nested if statements.
if ($code == 5) {
if ($animal == "bird") {
echo "DONE\n";
}
}
// Version 2: use single if-statement with logical AND.
if ($code == 5 && $animal == "bird") {
echo "DONE\n";
}DONE
DONE
Assert. In PHP assert statements are similar to if-statements in that we pass a condition to them. If the condition evaluates to true, nothing happens.
But If the condition is false, and we specify that the option zend.assertions is 1, then an error is reported.
$value1 = 20;
$value2 = 100;
$value3 = 100;
// This assertion will not display any error as the numbers are different.
assert($value1 != $value2);
// The 2 values are the same, so this assertion will display an error if// -d zend.assertions=1 is passed as a command-line argument to php.
assert($value2 != $value3);PHP Fatal error: Uncaught AssertionError: assert($value2 != $value3) in /.../program.php:12
Stack trace:
#0 /.../program.php(12): assert()#1 {main}
thrown in /.../program.php on line 12
Testing variables for certain conditions is commonly done in programs, and usually (but not always) this is done with if-statements. Match statements can also be used for more elegant code.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 7, 2023 (new example).