views:

78

answers:

4

In the PHP below if I compare a variable using == it works as I would expect it to, if I use != then my code breaks, can someone explain or help?

$_GET['p'] = 'home';

// DOES NOT work, it will always return "show JS" regardless to what string I have
if ($_GET['p'] != 'home' || $_GET['p'] != 'create.account'){
    echo 'show JS';
}else{
    echo 'do not show JS'; 
}

// Works as I would expect it to
if ($_GET['p'] == 'home' || $_GET['p'] == 'create.account'){
    echo 'do not show JS';
}else{
    echo 'show JS'; 
}
+9  A: 

$_GET['p'] can't be two different things at the same time. You say int the first expression; p not home or not create.account. Its always true. You should use && instead of ||

erenon
great that works
jasondavis
+1 simple misapplication of DeMorgan's Law (http://en.wikipedia.org/wiki/Demorgan%27s_law)
Dave DeLong
A: 
if ($_GET['p'] != 'home' && $_GET['p'] != 'create.account')
balint
because of http://en.wikipedia.org/wiki/Logical_disjunction(False OR True) == True
balint
+2  A: 
    (X != A) ||  (X != B)
≡  !(X == A) || !(X == B)
≡ !((X == A) &&  (X == B))

(X == A) && (X == B) is always false since the condition A != B but X cannot be both A and B at the same time. So !((X == A) && (X == B)) and your (X != A) || (X != B) is always true.

Gumbo
+3  A: 

You can see the problem by DeMorgans Laws for negation

!( A || B ) === (!A && !B)

The solution you give is impossible because there is no way for both statements to be false, because that would imply the string is equivalent to both the compared strings. The only way the else block would be hit is if both were false (because of the OR statement).

ghills