# The || trap

## Recommended Posts

Here is a logical OR || trap, I wonder how many people fall for this trap and are left scratching their heads?

```\$id = '0';
// Dont proceed if id is 1 or 0
if(\$id !='0' || \$id !='1'){

exit('It\s a trap');

}
?>
```

But making || to && makes it work.

Has anyone here made this mistake? lol

##### Share on other sites

When you use negative logic in the comparison, the and/or condition needs to be complemented. Which is why using negative logic should generally be avoided as humans don't do well reading or writing negative logic.

```if(\$id =='0' || \$id =='1'){
// the value was 0 or the value was 1
} else {
// the value was not 0 and it was not 1
}```

```if(\$id !='0' && \$id !='1'){
// the value was not 0 and it was not 1
} else {
// the value was 0 or the value was 1
}```

##### Share on other sites

a && b === !a || !b

a || b === !a && !b

If you can remember that, then you're good to go.

##### Share on other sites

Hahah, I've never fallen into that trap

##### Share on other sites

I've been there before, but I think I realized that it was at that point ... I needed to sleep.

##### Share on other sites

Here is a video from standford that explains why 2 statments with != and || will be always be true.

##### Share on other sites

Here is a video from standford that explains why 2 statments with != and || will be always be true.

\$x = 1;

\$y = 1;

if( \$x != 1 || \$x != \$y ) {

echo 'true';

}else{

echo 'not always!';

}

##### Share on other sites

huh? This always returns to the first echo. How is that not always true? Well I dont really understand myself.

```\$id = '0';
//
if(\$id !='0' || \$id !='1'){

echo "First echo";

} else {

echo "will never happen";

}```

##### Share on other sites

\$id = '0';

\$id !='0' || \$id !='1'

The literal is if \$id is not 0 or \$id is not 1. Only one of the two conditionals must hold true for the or to evaluate to true completely. So if \$id is not 0, it's true, but if \$id is not 1 it is also true.

##### Share on other sites

2 statments with != and || will be always be true.

This statement in and of itself is incorrect.

A != B || A != C will always be true only if B != C

##### Share on other sites

a && b === !a || !b

a || b === !a && !b

If you can remember that, then you're good to go.

This is called De Morgan's Law for the mathematically interested. It's fairly easy to prove, and other mathematical structures have this property as well.

##### Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.