PHP 7.4 : Null Coalescing Assignment Operator
20, December 2019

In PHP 7.0, we got new null coalescing operator (??) which is a syntactic sugar of using isset() for check a value for null. PHP 7.4 has brought new syntactic sugar to assign default value to a variable if it is null.


Lets say, we have a variable called $student_name which should contain student name in it. But for some reason, sometimes student name may can't be found (null value), so we need to assign default value to it before using it. In PHP <7.4 , we would do something like this:

<?php

$student_name = null;

$student_name = $student_name ?? 'Default Name';

var_dump($student_name);
// string(12) "Default Name"

In line 5, we are checking if $student_name has been set, if not we are assigning 'Default Name' to it.

In PHP 7.4, we can use Null Coalescing Assignment Operator (??=) to do the same:

<?php

$student_name = null;

$student_name ??= 'Default Name';

var_dump($student_name);

Above, Null Coalescing Assignment Operator checks if $student_name is null, if so it assign string(12) "Default Name" to it.


Best benefit of Null Coalescing Assignment Operator is when used for array element. lets say, we have an variable for a blog post which is array

$post = [
    'title' => 'The Greatest Blog Post',
    'body' => 'This is an awesome blog post'
];

// We want to assign default author name is not set in $post

$post['author_name'] ??= 'Default Name';

var_dump($post);
// array(3) {
// ["title"]=> string(22) "The Greatest Blog Post"
// ["body"]=> string(28) "This is an awesome blog post"
// ["author_name"]=> string(12) "Default Name" }

Write comment about this article: