Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP why (null === $variable) and not ($variable === null) in comparison? [duplicate]

Tags:

php

When reading Symfony2 code I came across this comparaison many times

if (null === $variable ) { ... }

I use

if ($variable === null ){ ... }

because I see it more readable.

Is there a wisdom behind using the first notation ?

like image 476
zizoujab Avatar asked Feb 19 '26 14:02

zizoujab


2 Answers

No compile/interpretting difference at all, it's pure code style.
It's also known as Yoda Conditions.

Conditions, Yoda

It helps prevent accidental assignments:

if ($foo = null) { ... }

would not cause a parse error, while will

if (null = $foo) { ... }

1st example: http://sandbox.onlinephpfunctions.com/code/fff14c285a18a7972a3222ff5af08da825760c10 2nd example: http://sandbox.onlinephpfunctions.com/code/118d494c17381d8e129ba005465bf84d9b8819bd

like image 22
Eldarni Avatar answered Feb 22 '26 02:02

Eldarni



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!