Search code examples
phpcoding-stylestrposboolean-operations

an elegant way to handle returning strpos 0 as TRUE


switch (true){
    case stripos($_SERVER['SERVER_NAME'],"mydomain.com", 0) :

        //do something 
        break;

        /*
        stripos returns 4 ( which in turn evaluates as TRUE )  
        when the current URL is www.mydomain.com
        */


    default:

        /*
        stripos returns 0 ( which in turn evaluates as FALSE )  
        when the current URL is mydomain.com
        */


}   

when stripos finds the needle in the haystack returns 0 or up. when stripos does not find the needle, it returns FALSE. There could be some advatages of this approach. But I don't like that!

I'm coming from VB background. There, instr function (which is the equivalent of strpos) returns 0 when it cannot find the needle and returns 1 or up if it finds it.

so the above code never causes a problem.

how do you elegantly handle this situation in PHP? What's the best practice approach here?

Also, on a different note, what do you think about using the

switch(true) 

Is that a good way to write code to begin with?


Solution

  • strpos returns false if the needle doesn't exist within the haystack. By default (using non-strict comparison), PHP will treat 0 and false as equivilant. You need to use strict comparison.

    var_dump (strpos ('The quick brown fox jumps over the lazy dog', 'dog') !== false); // bool (true)
    var_dump (strpos ('The quick brown fox jumps over the lazy dog', 'The') !== false); // bool (true)
    var_dump (strpos ('The quick brown fox jumps over the lazy dog', 'cat') !== false); // bool (false)