Hector Ordonez
Hector Ordonez

Reputation: 1104

What is the difference between $foo === TRUE and TRUE === $foo

I do understand that, in the following code...

$foo = TRUE;
$bar = 1;

if ($foo === TRUE)
{
    echo 'Foo';
}

if ($bar === TRUE)
{
    echo 'Bar';
}

... will only print Foo because of the Type comparison.

However, my question is regarding ...

if ($foo === TRUE)
{
    echo 'Foo1';
}
if (TRUE === $foo)
{
    echo 'Foo2';
}

... because as far as I know, they are the same, but I remember reading somewhere that they are not. Am I just dreaming weird stuff about PHP or is there actually a difference?

Thanks!

Upvotes: 3

Views: 334

Answers (2)

dkellner
dkellner

Reputation: 9936

It's the same - it's only that if you put $foo on right side you can be safe from that terrible mistake when you use only one "=" sign. So it's rather a good practice to use "left comparisons". Consider this:

//  These 4 lines intended for the same check
//  Notice the subtle differences!

    if("secret_thing" =  $password) {...}   // you get an error but that's it
    if("secret_thing" == $password) {...}   // this is perfect
    if($password == "secret_thing") {...}   // this is acceptable
    if($password =  "secret_thing") {...}   // you're deep in trouble, friend!

//

With literals on the left, the worst thing to happen is that you get an error message. No big deal. With literals on the right (and a small typo), burglars are right in your living room.

Actually, that typo is very easy to make, for example, if you work with Pascal / Delphi / Lazarus where you have ':=' for assignment and a simple '=' means comparison. And there's no alarm when you do it; PHP will think he understands you.

TLDR: it's a safeguard.

Side note: you can also use a comparison function to improve readability. But that one takes some extra microseconds so in high performance cases just stick to the good old "==" / "===" sign.

Upvotes: 6

Igoooor
Igoooor

Reputation: 407

They both are exactly the same

The same exactly they are ;)

Upvotes: 3

Related Questions