In PHP programs, we need to test variables to determine what to do next. This is done with the if
-keyword, along with elseif
and else
-statements.
With the if
-statement, we have a syntax that tests for a single condition. And with the match
-statement, we can check for multiple conditions, one on each line.
This program implements the same logical tests with the if
-keyword and then with the match
-keyword. We can see the two styles of code making the same checks.
if
-statement, elseif
and else
-statement. If the size if 10, we set result to "Ten".$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
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.
$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
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.
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.