Is this asterisk character in my switch the reason I'm having a paradox in the output?

197 views Asked by At

In a PHP script I have this code:

 $route = new Route($url);
 var_dump($route->getRouteIDs());
 
 echo "<br/>";
 $isValid = $route->isValid($url);
 var_dump($isValid);
 
 echo "<br/>";
 switch($isValid) {
     case '*':
         echo "wildcard route";
         break;
     case true:
         echo "real route";
         break;
     case false:
         echo "false route";
         break;
 }

This is the output:

array(1) { [0]=> string(2) "21" }

bool(true)

wildcard route

In the output, lines 1 & 2 are as expected. But to me, it looks like the results of lines 2 and lines 3 are contradicting each other.

Why is the switch being activated for the asterisk (*) character when the var_dump is saying the variable $isValid contains only a boolean 'true' value?

1

There are 1 answers

1
Barmar On

switch performs loose comparisons. In this case, true compares equal to any truthy value. You can see it with this simple test:

if ('*' == true) {
    echo "Wildcard route";
}

If you want strict comparisons, you'll have to write out the if/then/elseif statements, using === as the comparison operator.