Karem
Karem

Reputation: 18103

PHP: if(!$one == $two) doesn't work always?

Yes, this is just a question i would like to get an answer on. I experienced it a couple of times, where this:

if(!$one == $two){ echo "Not the same"; }else{ echo "The same"; }

Will not work, and

if($one == $two){ echo "The same"; }else{ echo "Not the same"; }

will work.

Why doesn't it work sometimes? I always need to recode like the second, when the first doesn't work.

Upvotes: 1

Views: 439

Answers (3)

Gazler
Gazler

Reputation: 84150

You need

if(!($one == $two))

This is because without the brackets, it is checking if $one is false and then checking if $two == $one. The following is the only time that it will work without the brackets. Evaluating to if (true == true) as !$one = true.

$one = false;
$two = true;

if (!$one == $two)
{
    echo "different";
}

Upvotes: 1

codaddict
codaddict

Reputation: 455072

! is having higher precedence than == so you should use parenthesis as:

if(!($one == $two))

Upvotes: 5

ChrisM
ChrisM

Reputation: 1124

You need to write

if(!($one == $two))

or

if($one != $two)

since the ! operator has a higher precedence than the == operator.

See also: http://www.php.net/manual/en/language.operators.precedence.php

Upvotes: 5

Related Questions