在数组上使用 PHP 的空合并运算符
using PHP's null coalescing operator on an array
我正在使用 http://php.net/manual/en/migration70.new-features.php 描述的 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
索引,其值为 "default".
$params=['address'=>'123 main street'];
$params['phone']??'default';
为什么不呢?
您没有向参数添加任何内容。您给定的代码只是生成一个未使用的 return 值:
$params['phone'] ?? 'default'; // returns phone number or "default", but is unused
因此,您仍然需要设置它:
$params['phone'] = $params['phone'] ?? 'default';
上述 @mrks 的正确答案可以缩短为:
$params['phone'] ??= 'default';
我正在使用 http://php.net/manual/en/migration70.new-features.php 描述的 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
索引,其值为 "default".
$params=['address'=>'123 main street'];
$params['phone']??'default';
为什么不呢?
您没有向参数添加任何内容。您给定的代码只是生成一个未使用的 return 值:
$params['phone'] ?? 'default'; // returns phone number or "default", but is unused
因此,您仍然需要设置它:
$params['phone'] = $params['phone'] ?? 'default';
上述 @mrks 的正确答案可以缩短为:
$params['phone'] ??= 'default';