Switch surprises
suggest changeSwitch statements use non-strict comparison to determine matches. This can lead to some nasty surprises. For example, consider the following statement:
switch ($name) {
case 'input 1':
$mode = 'output_1';
break;
case 'input 2':
$mode = 'output_2';
break;
default:
$mode = 'unknown';
break;
}
This is a very simple statement, and works as expected when $name is a string. Before PHP 8, switch compared with ==, so integer 0 matched the first case: the string "input 1" was cast to integer 0. Since PHP 8, a number compared with a non-numeric string is compared as a string, so 0 does not match "input 1" and default runs.
There are a few solutions to this problem:
Explicit casting
The value can be typecast to a string before comparison:
switch ((string)$name) {
// cases
}
Or a function known to return a string can also be used:
switch (strval($name)) {
// cases
}
Both of these methods ensure the value is of the same type as the value in the case statements.
Avoid switch
Using an if statement will provide us with control over how the comparison is done, allowing us to use strict comparison operators:
if ($name === "input 1") {
$mode = "output_1";
} elseif ($name === "input 2") {
$mode = "output_2";
} else {
$mode = "unknown";
}