user9059272
user9059272

Reputation:

How does nesting null coalescing operator(??) work in PHP? Need step-by-step explanation of execution flow

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

?>

Upvotes: 2

Views: 2012

Answers (3)

AndrewRMillar
AndrewRMillar

Reputation: 662

You could translate the null coalescing operator in a series of if/elseif/else statements. From you example:

echo $foo ?? $bar ?? $baz ?? $qux; // outputs 1

Translated into if/else statements:

<?php
$foo = null;
$bar = null;
$baz = 1;
$qux = 2;

if (isset($foo)) {
   echo $foo;
}
else if (isset($bar)) {
   echo $bar;
}
else if (isset($baz)) {
   echo $baz;
} 
else { 
    echo $qux;
}

Personaly I use the null coalescing operator very sparingly and nesting it seems like a recipe for disaster.

The null coalescing operator (apart from having a really annoying name), does not improve the readability of your code. I don't think the few lines spared is worth the extra mental overhead it requires when reading your code. Or is worth having other people having trouble reading/comprehend your code. So be a nice programmer to your fellow programmers and use the null coalescing operator sparingly and never nest it.

Upvotes: 1

user9059272
user9059272

Reputation:

It works in similar manner as it works in its basic usage.

The execution flow will be as follows :

  1. It checks isset($foo) it's not been set, it contains NULL so, go for $bar
  2. It checks isset($bar) it's not been set, it's too contains NULL so, go for $baz
  3. It checks isset($baz) it's been set, it contains the value 1 so, it gets printed and execution stops.

Upvotes: 1

Philipp
Philipp

Reputation: 15629

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).

Upvotes: 7

Related Questions