EDIT : My bad, I made a mistake, when I said null in this post I meant to say null or empty or zero or false or whatever that makes (!$x) true.
with a friend, we are trying to find the best way to affect a value to a variable if this variable is null. We want to do this:
if (!$x)
$x = 5;
My friend suggested a one line solution:
!$x && $x = 5;
Here, if $x is null, then $x = 5 will be interpreted by PHP so $x will contain 5. If $x is not null the second part of the line won't be read and $x will keep its old value.
Resume:
$x null: one get, one comparison, one set.
$x not null: one get, one comparison
I tryied to do cleaner AND better. First, I came to this:
$x = $x ? $x : 5;
but here if $x were previously not null, then PHP will do an extra affectation ($x = $x), plus, this line is longer than the previous one. Resume:
$x null: one get, one comparison, one set.
$x not null: two get, one comparison, one set ($x = $x).
Then I came to this:
$x = $x ?: 5;
We have less operations than the previous one and we have one character less than the first one. Resume:
$x null: one get, one comparison, one set.
$x not null: one get, one comparison, one set ($x = $x).
But my question is, when PHP have to do this:
$x = $x;
Is it really doing it? If not, the third solution (the last one) is the best. Otherwise, the first solution is the best one.
Is there other solutions to solve this problem ?
Thank you.
"the best" solution is always to compare types
if ($x)
This if is equivalent of
if ($x == true)
but it is not the same as
if ($x === true)
This:
if (!$x)
is the same as
if ($x != true)
Showing you the problem behind this tries to short it:
$x = false;
if (!$x)
$x = 5;
false
and null
evaluate both to true in (!$x)
.
When you want to be sure, you don't shorten it. The best is strict comparison:
$x = ($x !== null) ? $x : 5;
As deceze already said, shortening the code might lead to confusion. $x
can have different values which result in unexpected behaviour when you don't stricly compare it to the desired content. Examples:
$x = '';
$x = null;
$x = false;
$x = 0;
$x = 1;
$x = new stdClass;
What happens, when you put all these into an if without strict comparison (if ($x)
) ?
Make plenty use of:
if ($x === null)
if ($x !== false)
if ($x !== 0)
if ($x instanceof stdclass)