I'm using PHP 7.2.0
I've understood the normal basic usage of null coalescing operator(??) but I'm not able to understand the execution flow and functionality of when null coalescing operator(??) is nested.
Please consider below code example and explain me the execution-flow in step-by-step manner.
<?php
$foo = null;
$bar = null;
$baz = 1;
$qux = 2;
echo $foo ?? $bar ?? $baz ?? $qux; // outputs 1
?>
I think your example becomes cleaner, if you add parens around the single steps of the null coalescing operator.
echo ($foo ?? ($bar ?? ($baz ?? $qux)));
Basically it's the same as executing from left to right.
The null coalescing operator is right associative. That means that operations are grouped from right to left. I.e, the expression a ?? b ?? c
is evaluated as a ?? (b ?? c)
.