What Is the Null Coalescing Assignment Operator in PHP?

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'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.