using PHP's null coalescing operator on an array

荒凉一梦 提交于 2019-12-04 06:02:16

问题


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?


回答1:


You don't add anything to params. Your given code simply generates an unused return value:

$params['phone'] ?? 'default'; // returns phone number or "default", but is unused

Thus, you will still have to set it:

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


来源:https://stackoverflow.com/questions/53342617/using-phps-null-coalescing-operator-on-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!