处理返回的strpos 0的优雅方法为TRUE

Ave*_*Joe 2 php coding-style strpos boolean-operations

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
        */


}   
Run Code Online (Sandbox Code Playgroud)

当stripos发现大海捞针返回0或以上时.当stripos找不到针时,它返回FALSE.这种方法可能有一些优点.但我不喜欢那样!

我来自VB背景.在那里,instr函数(相当于strpos)在找不到针时返回0,如果找到则返回1或者向上.

所以上面的代码永远不会导致问题.

你如何在PHP中优雅地处理这种情况?这里最好的做法是什么?

另外,在另一个注释中,您如何看待使用

switch(true) 
Run Code Online (Sandbox Code Playgroud)

这是编写代码的好方法吗?

Gor*_*onM 5

如果大海捞针内不存在针,则strpos返回false.默认情况下(使用非严格比较),PHP会将0和false视为等效.你需要使用严格的比较.

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)
Run Code Online (Sandbox Code Playgroud)