views:

69

answers:

3

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.

+5  A: 

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

ChrisM
+5  A: 

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

if(!($one == $two))
codaddict
+1  A: 

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";
}
Gazler