1

I read often in examples and some codes this order in if conditions:

if (false === $var)
if (null  === $var) 

instead of

if ($var === false)
if ($var === null)

What is the main difference? Which one should i preffer?

smartcoderx
  • 1,021
  • 2
  • 14
  • 32

3 Answers3

3

These are called Yoda Conditions. The "advantage" being you can not accidentally assign a value to a variable when checking its value.
An example would be:

if( 100 = $var ) would give you a syntax error. So the argument is that Yoda Conditions guarantee youre in fact checking a value and not setting a value. This pretty much sums it up.

Zac Ball
  • 198
  • 8
0

Base in my knowledge, this is the preferred syntax for today.

if (false === $var)
if (null  === $var)

Because when you accidentally get a typo like this:

if ($var = false)

Which you assigned false to the variable $var, it's hard to trace this bug when you are running your code.

WaduNoop
  • 65
  • 1
  • 2
  • 14
  • The other hassle is when you have that typo, it doesn't generate any errors. That's why it's hard to trace it. I hope this helps. – WaduNoop Sep 02 '15 at 05:58
0

if (false === $var) if (null === $var)

This is the preferred and best way of checking the values in if conditions Because if we use the

$var === false

manual typing errors like

$var = false might accidentally assign value false to the variable $var and will be undetectable.

in case of false= $var the compiler will throw a definite error and we can identify the bug easily

Vignesh
  • 99
  • 7