开发者

Inverting Logical AND Condition

I'm working on the following code:

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

else
{
    // do something
}

The logic of this condition is working just fine, however, I would prefer if I could get rid of the empty if block while evaluating the second condition only if the first one yields true - otherwise the preg_grep() call will throw the following notice when $data has more than one dimension:

Notice: Array to string conversion

I know I could use the error suppression operator or some other hacky approaches, but I have the feeling that I'm missing something trivial. Can someone help me out, please?


First, obvious way:

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

else
{
    // do something
}

Second, correct way

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)))

{ // do something }


if (! (
   count($data) == count($data, COUNT_RECURSIVE) && 
   count(preg_grep('~^@~', $data)) > 0
   )

Wrap the entire group of conditions and stick ! at the start. Line breaks are for readability. I removed the unnecessary () around the individual conditions as well.


I'm not entirely clear what you're asking, but I think you want:

// $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
}

With this, the block executes if ((count($data) == count($data, COUNT_RECURSIVE)) && (count(preg_grep('~^@~', $data)) > 0)) is false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜