views:

177

answers:

5

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

A: 

if your code is:

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

any value or even null value can enter this condition. you can change || to && meaning any string which is not equal to "1" and "2" can enter you condition

Treby
+2  A: 

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'))
Doug Neiner
Ahh it all makes sense now, thanks :)
kwhohasamullet
A: 

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 &&.

David Grayson
A: 
Jason George
A: 

Try:

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

If you use != in both statements, then you need to use && instead of || to make sure both statements get evaluated.

Essentially, using || means that the first statement gets evaluated and if it is false, then PHP will ignore the second statement because you are using OR. But if you use &&, then PHP will be sure to evaluate both != statements.

Stinky Tofu