在数组上使用 PHP 的空合并运算符

use*_*531 9 php arrays ternary

我正在使用http://php.net/manual/en/migration70.new-features.php描述的 PHP 空合并运算符。

\n\n
Null coalescing operator \xc2\xb6\nThe 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.\n\n<?php\n// Fetches the value of $_GET[\'user\'] and returns \'nobody\'\n// if it does not exist.\n$username = $_GET[\'user\'] ?? \'nobody\';\n// This is equivalent to:\n$username = isset($_GET[\'user\']) ? $_GET[\'user\'] : \'nobody\';\n\n// Coalescing can be chained: this will return the first\n// defined value out of $_GET[\'user\'], $_POST[\'user\'], and\n// \'nobody\'.\n$username = $_GET[\'user\'] ?? $_POST[\'user\'] ?? \'nobody\';\n?>\n
Run Code Online (Sandbox Code Playgroud)\n\n

我注意到以下内容不会产生我预期的结果,即添加一个值为“默认”的新phone索引。$params

\n\n
$params=[\'address\'=>\'123 main street\'];\n$params[\'phone\']??\'default\';\n
Run Code Online (Sandbox Code Playgroud)\n\n

为什么不?

\n

mrk*_*rks 14

您无需向 params 添加任何内容。您给定的代码只是生成一个未使用的返回值:

$params['phone'] ?? 'default'; // returns phone number or "default", but is unused
Run Code Online (Sandbox Code Playgroud)

因此,您仍然需要设置它:

$params['phone'] = $params['phone'] ?? 'default';
Run Code Online (Sandbox Code Playgroud)


小智 12

上面@mrks的正确答案可以缩短为:

    $params['phone'] ??= 'default';
Run Code Online (Sandbox Code Playgroud)

RFC:空合并等于运算符