Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if or statement not working

We are trying to use the below piece of code

if (($_GET['1'] != "1") || ($_GET['1'] != "2")) {

When we try this no matter what value the variable has it will evaluate as true even when data is entered that is false. When we use

if (($_GET['1'] == "1") || ($_GET['1'] == "2")) {

and put in data that will make it return false it works correctly. We have reversed the way that the if statement goes just so we can get this working but i would like to know why this doesnt work, if it is something im doing wrong or a limitation within php with the or and the not equal operators

Thanks

like image 632
kwhohasamullet Avatar asked Mar 09 '26 19:03

kwhohasamullet


2 Answers

Your first test is saying this:

If $_GET['1'] is anything other than "1" OR $_GET['1'] is anything other than "2"

The expression will always pass: If it equals 1 it will pass the != '2' test on the second half of your if statement. If it equals 2 it will pass the != '1' test on the first half, and never make it to the second half of the test.

The second test simply says:

If $_GET['1'] equals "1" OR $_GET['1'] equals "2" then the expression should pass

You probably want this expression, which will pass only if neither parameter holds the correct value:

if(($_GET['1'] != '1') && ($_GET['1'] != '2'))
like image 125
Doug Neiner Avatar answered Mar 12 '26 10:03

Doug Neiner


The expression below will always evaluate to TRUE, because either x is not 1 or x is not 2. There is no way that x can equal both 1 and 2 at the same time!

($x != 1) || ($x != 2)

The opposite of

($x == 1) || ($x == 2)

is

($x != 1) && ($x != 2)

Note that you have to change the || to a &&.

like image 22
David Grayson Avatar answered Mar 12 '26 10:03

David Grayson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!