dptn69182 2014-03-03 07:53
浏览 83
已采纳

什么是检查多个变量ALL在IF语句中是否等于相同值的简写方法? (PHP)

Is there a shorthand way of writing the code below?

if (($tstat=='no_prices')&&($l1stat=='no_prices')&&($l2stat=='no_prices')&&($l3stat=='no_prices'))
{                                   
    //do something
}

I tried using the below code,but it did something when one of the variables was not equal to 'no_prices'.

if (($tstat && $l1stat && $l2stat && $l3stat)=='no_prices')
{
    //do something
}

To check that the strings weren't causing problems I tried substituting 0 for 'no_prices' and 1 for other values, but the result was the same.

  • 写回答

8条回答 默认 最新

  • dousong1992 2014-03-03 09:25
    关注

    array_flip is several times faster than array_unique:

    function all_equal($arr, $value) {
      return array_keys(array_flip($arr)) == array($value);
    }
    
    $arr = array($tstat, $l1stat, $l2stat, $l3stat);
    
    echo all_equal($arr, 'no_prices');
    

    A quick profile for the answers given thus far, for 1000 iterations on array length 1000:

      array_flip: 0.07321620 seconds
    array_unique: 0.32569408 seconds
         foreach: 0.15136194 seconds
    array_filter: 0.41404295 seconds
    

    The code used to profile is here: http://codepad.org/szgNfWHe

    Note: As @cypherabe rightly points out, array_flip does not overtake array_unique until the array has at least 5 elements, and does not overtake foreach until the array has at least 10 elements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题