use*_*531 9 php arrays ternary
我正在使用http://php.net/manual/en/migration70.new-features.php描述的 PHP 空合并运算符。
\n\nNull 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?>\nRun Code Online (Sandbox Code Playgroud)\n\n我注意到以下内容不会产生我预期的结果,即添加一个值为“默认”的新phone索引。$params
$params=[\'address\'=>\'123 main street\'];\n$params[\'phone\']??\'default\';\nRun Code Online (Sandbox Code Playgroud)\n\n为什么不?
\nmrk*_*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)