What is the difference between putting the null in front of or behind the variable we are comparing?
There is no difference except a syntax convention.
This is true both for the one who writes the code to avoid typing errors, as for the Parser (at least in PHP) that tokenizes the source code to assemble the syntax tree that is then compiled to bytecode that then interprets it to opcode (assembler from the platform)
A constant such as number 42 or null is a token that has a rule (in the parser) by which it can not be followed by an assignment token (un =) but by a comparison token (a == )
Why is it being used or recommended?
I explain with the number 42 to make the effect of this practice clearer. in their homes they can use null
in PHP (and other languages) is generally used to avoid assignment errors.
#!/usr/bin/env php
<?php
$value = 40;
if ($value=42) :
echo "$value es 42".PHP_EOL;
else :
echo "$value NO es 42".PHP_EOL;
endif;
Result:
$ ./yodacondition.php
42 es 42
It's a simple example and we can infer the value of $value
before if
is 40
so the typing error (put =
instead of ==
) is evident.
But this error would not be so evident if $ value comes from another side.
Instead using Yoda Conditions ( link )
#!/usr/bin/env php
<?php
$value = 40;
if (42=$value) :
echo "$value es 42".PHP_EOL;
else :
echo "$value NO es 42".PHP_EOL;
endif;
Result:
$ ./yodacondition2.php
PHP Parse error: syntax error, unexpected '='
This is because 42 is a constant and can not be assigned a value.
What the compiler optimizes seems to me to be an urban myth, since the compiled languages usually have optimizers that create comparison tables and conditional jump internally for this type of if then else.
Edit 2: in the first example $value=42
not only assigns the value 42
to $value
but returns true
satisfying the condition of if