26
loading...
This website collects cookies to deliver better user experience
Just the Gist
Control structures are ways we can control the flow of the execution of our codes. If-statements has a lot of power, we can control every granular aspect of our code. But it can become repetitive when comparing one value against many different conditions. Switch statements took care of that. But this structure could still be improved upon with strict comparisons and less boiler-plate-like code. That's where match statements come in.
switch
was introduced with PHP way back at version 4. It let us check a value or case
and execute a block of code based on it. In a way, it is similar to the if
statement, but let's us avoid many else-if statements. In the PHP language, the switch statement does a loose comparison, so it automatically casts the value to the type of the case. Here's an example of that:<?php
$number = "3";
switch ($number) {
case 0:
case 1:
case 2:
echo "The number is 0, 1 or 2.";
break;
case 3:
echo "Alright, this is 3. Regardless if it's a string or a number.";
break;
default:
echo "I... I don't know what to do with this: " . $number;
break;
}
// Outputs: "Alright, this is 3. Regardless if it's a string or a number.
match
control structure! match
statement is a more strict version of switch
and it returns values our way. So let's take the above code and see what match does:<?php
$number = "3";
echo match($number) {
0, 1, 2 => "The number is 0, 1 or 2.",
3 => "Alright, this is 3. It's a number, this I know!",
default => "I... I don't know what to do with this: " . $number
};
// Outputs: I... I don't know what to do with this: 3
match
statement is a bit more strict it will only match the value if it's also the same type as the case. So, if you want to match a string, you have to use quotes. And if you want to match a number, you have to use a number. Also, it takes less code to write than the switch statement. Now, which one is better? That depends if there is need for more strict case checking or not. match
with conditional-based cases:<?php
$number = "3";
echo match(true) {
0 <= $number && $number < 3 => "The number is 0, 1 or 2.",
$number == 3 => "Alright, this is 3. Regardless if it's a string or a number.",
default => "I... I don't know what to do with this: " . $number
};
// Outputs: Alright, this is 3. Regardless if it's a string or a number.
match
case to do an equal
comparison with auto-casting. This means we can see that our "3"
is equal to 3
- if it was actually that way that we wanted that particular case to go. To use conditional-based cases, we set the match-parameter to true
.