Jump to content

Recommended Posts

Well, first off if you're working with integers you shouldn't be quoting them.

 

<?php
$number = 1;

if ($number != 1 || $number != 2) {
  echo "hello";
}
?>

 

Secondly, you're using an OR operator (||), this means that if it doesn't equal 1 OR 2 then display "hello". Well, it doesn't equal 2, so the expected result is correct.

 

<?php
$number = 1;

if ($number != 1 && $number != 2) {
  echo "hello";
}
?>

 

You want to use the AND operator (&&) for your expected result.

Edit: In case you need to see the same answer again ...

 

Because you are using negative logic (testing is something is not equal) and OR'ing the results.

 

What does your code evaluate to when you put the actual value in?

 

if ('1' != "1" || '1' != "2") 

 

'1' is not equal to '2' and the statement is TRUE and executes the echo.

 

You would actually need to use && (AND) to make the logic correct -

 

if ('1' != "1" && '1' != "2") 

 

It is generally better and clearer to use positive logic -

 

if($number == "1" || $number == "2") 
{
    // the value was one of the choices
    echo "hello";
} else {
    // the value was not one of the choices 
}

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.