Jump to content

Why does this not work


stuckwithcode

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 
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.