Jump to content

The || trap


keldorn

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

Link to comment
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
}

 

Link to comment
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.

Link to comment
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.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.