【问题标题】:Inverting Logical AND Condition反转逻辑与条件
【发布时间】:2011-08-21 08:33:44
【问题描述】:

我正在编写以下代码:

// $data has only one dimension AND at least one of its values start with a "@"
if ( (count($data) == count($data, COUNT_RECURSIVE))
  && (count(preg_grep('~^@~', $data)) > 0) )
{
    // do nothing
}

else
{
    // do something
}

这个条件的逻辑工作得很好,但是,我希望我可以摆脱空的 if 块,同时仅在第一个条件为真时评估第二个条件 - 否则 preg_grep() 调用将当$data 具有多个维度时,抛出以下通知:

注意:数组到字符串的转换

我知道我可以使用错误抑制运算符或其他一些 hacky 方法,但我觉得我错过了一些微不足道的东西。有人可以帮帮我吗?

【问题讨论】:

  • && 已经短路了...不是吗?

标签: php arrays multidimensional-array if-statement conditional-operator


【解决方案1】:

首先,显而易见的方式:

if (!( (count($data) == count($data, COUNT_RECURSIVE))
    && (count(preg_grep('~^@~', $data)) > 0)) )
{
    // everything is cool, nothing to do
}

else
{
    // do something
}

第二种,正确方式

if ((count($data) < count($data, COUNT_RECURSIVE))
 || (count(preg_grep('~^@~', $data)) == 0))
{
    // everything is cool, nothing to do
}

else
{
    // do something
}

【讨论】:

    【解决方案2】:

    我不完全清楚你在问什么,但我认为你想要:

    // $data has only one dimension AND at least one of its values start with a "@"
    if (!((count($data) == count($data, COUNT_RECURSIVE))
      && (count(preg_grep('~^@~', $data)) > 0)))
    {
        // do something
    }
    

    这样,如果((count($data) == count($data, COUNT_RECURSIVE)) &amp;&amp; (count(preg_grep('~^@~', $data)) &gt; 0)) 为假,该块就会执行。

    【讨论】:

      【解决方案3】:
      if (! (
         count($data) == count($data, COUNT_RECURSIVE) && 
         count(preg_grep('~^@~', $data)) > 0
         )
      

      包装整个条件组并坚持!在开始时。换行符是为了便于阅读。我也删除了个别条件周围不必要的 ()。

      【讨论】:

      • 谢谢,我很少使用这个运算符,有时我什至忘记了它的存在。
      【解决方案4】:
      if (!((count($data) == count($data, COUNT_RECURSIVE)) && (count(preg_grep('~^@~', $data)) > 0)))
      

      { // 做一点事 }

      【讨论】:

        猜你喜欢
        • 2017-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多