首頁  >  文章  >  後端開發  >  在php中,三元運算子和空合併運算子之間的差異是什麼?

在php中,三元運算子和空合併運算子之間的差異是什麼?

王林
王林轉載
2023-08-20 11:21:111208瀏覽

在php中,三元運算子和空合併運算子之間的差異是什麼?

三元運算子

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

語法

(condition) ? expression1 : expression2;

等價表達式

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

如果條件為真,則傳回表達式1的結果,否則傳回表達式2的結果。條件或表達式中不允許使用void。

空合併運算子

空合併運算子用於在變數為空時提供非空值。

語法

(variable) ?? expression;

等價表達式

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

如果變數為空,則傳回表達式的結果。

範例

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

輸出

not passed
not passed

以上是在php中,三元運算子和空合併運算子之間的差異是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除