在数组上使用PHP的空合并运算符 [英] using PHP's null coalescing operator on an array

查看:70
本文介绍了在数组上使用PHP的空合并运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 http://php所述的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';
?>

我注意到以下内容并没有产生预期的结果,那就是向 $ params 添加一个新的 phone 索引,其值为默认".

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';

为什么不呢?

推荐答案

您无需在参数中添加任何内容.您给定的代码只是生成一个未使用的返回值:

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';

这篇关于在数组上使用PHP的空合并运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆