PHP 中三元運算子和空值合併運算子的區別


三元運算子

三元運算子用於將 if else 語句替換為一個語句。

語法

(condition) ? expression1 : expression2;

等價表示式

if(condition) {
   return expression1;
}
else {
   return expression2;
}

如果條件為真,則返回 expression1 的結果,否則返回 expression2 的結果。condition 或 expression 中不允許使用 void。

空值合併運算子

空值合併運算子用於在變數為 null 情況下提供非 null 值。

語法

(variable) ?? expression;

等價表示式

if(isset(variable)) {
   return variable;
}
else {
   return expression;
}

如果變數為 null,則返回表示式的結果。

示例

<!DOCTYPE html>
<html>
<head>
   <title>PHP Example</title>
</head>
<body>
   <?php
      // fetch the value of $_GET['user'] and returns 'not passed'
      // if username is not passed
      $username = $_GET['username'] ?? 'not passed';
      print($username);
      print("<br/>");
      // Equivalent code using ternary operator
      $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
      print($username);
      print("<br/>");
   ?>
</body>
</html>

輸出

not passed
not passed

更新於: 2020 年 1 月 6 日

430 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告