doufu6504 2012-04-08 18:04
浏览 120
已采纳

处理返回的strpos 0的优雅方法为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?

  • 写回答

1条回答

  • dongseshu0698 2012-04-08 20:00
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作