Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

boolean

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!

like image 560
Hector Ordonez Avatar asked Jan 30 '26 08:01

Hector Ordonez


2 Answers

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.

like image 137
dkellner Avatar answered Feb 01 '26 22:02

dkellner


They both are exactly the same

The same exactly they are ;)

like image 30
Igoooor Avatar answered Feb 01 '26 23:02

Igoooor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!