簡體   English   中英

在數組上使用 PHP 的 null 合並運算符

[英]using PHP's null coalescing operator on an array

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

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索引,其值為“默認”。

$params=['address'=>'123 main street'];
$params['phone']??'default';

為什么不?

以上來自@mrks的正確答案可以縮短為:

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

RFC:Null 合並相等運算符

您不添加任何參數。 您的給定代碼只是生成未使用的返回值:

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

因此,您仍然必須設置它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM