PHP if or statement not working
We are trying to use the below piece of code
if (($_G开发者_如何学GoET['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
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'))
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 &&.
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.
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
Without knowing the intention of the statement, or what input you started with (or how you revised it), I can't say for certain what the issue is.
That said, the first statement will only evaluate to FALSE
if $_GET['1']
is equal to 1 and $_GET['2']
is equal to 2.
The second statement will only evaluate to FALSE
if $_GET['1']
is not equal to 1 and $_GET['2']
is not equal to 2.
I'm guessing what you wanted on your first statement was
if (($_GET['1'] != "1") && ($_GET['2'] != "2")) {
which evaluates to FALSE
unless $_GET['1']
is equal to 1 and $_GET['2']
is equal to 2.
精彩评论