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

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名