What Is Null Coalescing Assignment = Operator in PHP 7.4

What is null coalescing assignment ??= operator in PHP 7.4

From the docs:

Coalesce equal or ??=operator is an assignment operator. If the left parameter is null, assigns the value of the right paramater to the left one. If the value is not null, nothing is done.

Example:

// The folloving lines are doing the same
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
// Instead of repeating variables with long names, the equal coalesce operator is used
$this->request->data['comments']['user_id'] ??= 'value';

So it's basically just a shorthand to assign a value if it hasn't been assigned before.

PHP Elvis operator vs null coalescing operator

When your first argument is null, they're basically the same except that the null coalescing won't output an E_NOTICE when you have an undefined variable. The PHP 7.0 migration docs has this to say:

The null coalescing operator (??) has been added as syntactic sugar
for the common case of needing to use a ternary in conjunction with
isset(). It returns its first operand if it exists and is not NULL;
otherwise it returns its second operand.

Here's some example code to demonstrate this:

<?php

$a = null;

print $a ?? 'b'; // b
print "\n";

print $a ?: 'b'; // b
print "\n";

print $c ?? 'a'; // a
print "\n";

print $c ?: 'a'; // Notice: Undefined variable: c in /in/apAIb on line 14
print "\n";

$b = array('a' => null);

print $b['a'] ?? 'd'; // d
print "\n";

print $b['a'] ?: 'd'; // d
print "\n";

print $b['c'] ?? 'e'; // e
print "\n";

print $b['c'] ?: 'e'; // Notice: Undefined index: c in /in/apAIb on line 33
print "\n";

The lines that have the notice are the ones where I'm using the shorthand ternary operator as opposed to the null coalescing operator. However, even with the notice, PHP will give the same response back.

Execute the code: https://3v4l.org/McavC

Of course, this is always assuming the first argument is null. Once it's no longer null, then you end up with differences in that the ?? operator would always return the first argument while the ?: shorthand would only if the first argument was truthy, and that relies on how PHP would type-cast things to a boolean.

So:

$a = false ?? 'f'; // false
$b = false ?: 'g'; // 'g'

would then have $a be equal to false and $b equal to 'g'.

Difference between PHP ??, ?:, and ??=

To combine all answers already made in former questions. With ?? you check for existence and not being null, with ?: you check for true/false.

$result = $a ?? $b

is the same as:

if (isset($a) && !is_null($a)) {
$result = $a;
} else {
$result = $b;
}

The ??= is a shortcut for ?? and it works like .= or += as well, which means you can shorten

$a = $a ?? $b;

to

$a ??= $b;

The ?: is a shortcut for the ternary operator which is also a shortcut:

if ($a) {
$result = $a;
} else {
$result = $b;
}

is the same as:

$result = $a ? $a : $b;

is the same as:

$result = $a ?: $b;

You could both describe as: The first operand is the value to check, and if this one is useful, take it, if not, take the second as default.

You can concatenate them like this one:

$user = $_POST['user'] ?? $_SESSION['user'] ?? $_COOKIE['user'] ?? '';

Which means something like: If you get the username in the POST array because of just logging in, fine, take it, if not, see whether the user is already logged on and in the session, if yes, take it, if not, maybe we have a user in the Cookies (checked the "remember me" checkbox while last login), and if this fails also, well, then leave it empty.

Of course you have to check the password too. ;-)

Edit: I use the ?: operator very often to ensure that I have a certain datatype in a variable. There are a lot PHP functions that give back maybe a string or an array if successful, but false if some error occured. Instead of having false as result, having the empty string or empty array is more consistent. As example, scandir should give back an array, but gives back false if an error occures. So you can do this:

$files = scandir('/some/random/folder') ?: [];

Then $files will always be an array, even if scandir fails. Well, then it's an empty array, but maybe better than checking later against false. In fact, we already did it with very low effort. Then you can use a foreach loop without some wrapping if. If scandir failed, the array is empty and the loop will just do nothing.

Is there an operator meaning ??= in PHP?

Yes! This exists in PHP 7.4 now.

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';


Related Topics



Leave a reply



Submit