stuckwithcode Posted March 2, 2010 Share Posted March 2, 2010 Why does this script still echo hello when to me it shouldn't <?php $number = "1"; if ($number != "1" || $number != "2") { echo "hello"; } ?> thanks Quote Link to comment https://forums.phpfreaks.com/topic/193883-why-does-this-not-work/ Share on other sites More sharing options...
inversesoft123 Posted March 2, 2010 Share Posted March 2, 2010 why you are using OR if you dont wanna print hello use && lol Quote Link to comment https://forums.phpfreaks.com/topic/193883-why-does-this-not-work/#findComment-1020371 Share on other sites More sharing options...
Wolphie Posted March 2, 2010 Share Posted March 2, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/193883-why-does-this-not-work/#findComment-1020372 Share on other sites More sharing options...
stuckwithcode Posted March 2, 2010 Author Share Posted March 2, 2010 Thanks both for the help, problem solved Quote Link to comment https://forums.phpfreaks.com/topic/193883-why-does-this-not-work/#findComment-1020374 Share on other sites More sharing options...
PFMaBiSmAd Posted March 2, 2010 Share Posted March 2, 2010 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 } Quote Link to comment https://forums.phpfreaks.com/topic/193883-why-does-this-not-work/#findComment-1020376 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.