What Is the Null Coalescing Assignment Operator in PHP?

PHP null coalescing assignment operator (??=) explained

Starting with PHP 7.4+, you can use the null coalescing assignment operator (??=). It is a shorthand to assign a value to a variable if it hasn't been set already. Consider the following examples, which are all equivalent:

// using the ternary operator
$x = (isset($x) ? $x : $y);
// PHP 7+
// using the null coalescing operator
$x = $x ?? $y;
// PHP 7.4+
// using the null coalescing assignment operator
$x ??= $y;

The null coalescing assignment operator only assigns the value if $x is null or not set. For example:

// PHP 7.4+
$x = 'foo';
$x ??= 'bar';

echo $x; // 'foo'
// PHP 7.4+
$x = null;
$x ??= 'bar';

echo $x; // 'bar'
// PHP 7.4+
$x ??= 'bar';

echo $x; // 'bar'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.