I’m trying to use this code to print a text based on $num variable value, but when I assign a non-numeric value to it the output is much like I assigned a positive number, shouldn’t the output here be ‘Undefined Value’? I mean why isn’t executing the default case?
$num = ";";
match (true) {
$num < 0 => print 'negative number',
$num == 0 => print 'zero',
$num > 0 => print 'positive number',
default => 'Undefined Value',
};
//Output: positive number
2
Answers
I did it like this and it worked:
A simpler test case:
Demo
If we check how comparison operators work, we understand that both operators are converted to numbers, but that isn’t true any more starting on PHP/8.0:
Demo
I suspect that documentation needs a fix and current rules are that right side operator is cast to string. As such,
;
is3B
in ASCII and0
is30
(thus "smaller").Regarding your code, you could add a numeric check like this:
But perhaps (and bear in mind that this is pretty much subjective) a match expression does not provide the leanest syntax for this use case and good old set of if/else can to the work just as fine. You can easily call
is_numeric()
once and avoid IEEE precision errors: