Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using PHP's null coalescing operator on an array

I am using PHP's null coalescing operator described by http://php.net/manual/en/migration70.new-features.php.

Null coalescing operator ¶
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.

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

I noticed the following doesn't produce my expected results which was to add a new phone index to $params whose value is "default".

$params=['address'=>'123 main street'];
$params['phone']??'default';

Why not?

like image 542
user1032531 Avatar asked Mar 04 '26 21:03

user1032531


1 Answers

The correct answer above from @mrks can be shortened to:

$params['phone'] ??= 'default';

RFC: Null coalesce equal operator

like image 127
Dmitry Bordun Avatar answered Mar 06 '26 13:03

Dmitry Bordun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!