JasonDavis
JasonDavis

Reputation: 48933

PHP if/else errors

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'; 
}

Upvotes: 0

Views: 447

Answers (4)

Gumbo
Gumbo

Reputation: 655239

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

Upvotes: 2

Gavin H
Gavin H

Reputation: 10482

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

Upvotes: 3

balint
balint

Reputation: 3431

if ($_GET['p'] != 'home' && $_GET['p'] != 'create.account')

Upvotes: 0

erenon
erenon

Reputation: 19118

$_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 ||

Upvotes: 9

Related Questions