PHP 中的雙問號

Sheeraz Gul 2023年1月30日
  1. 在 PHP 中使用雙問號作為 Null Coalescing 運算子
  2. 在 PHP 中的表單值上使用雙問號
PHP 中的雙問號

雙問號在 PHP 中稱為 Null Coalescing 運算子。它是在 PHP7 中引入的。

雙問號返回運算元的值,即 not Null

它從左到右檢查運算元並返回第一個 non-Null 值。

如果需要結合使用三元,可以使用 Null Coalescing 運算子;在 PHP7 之前,我們使用 PHP 內建函式 isset()?: 而不是 ??

在 PHP 中使用雙問號作為 Null Coalescing 運算子

<?php
$Temp = null;
$Demo = $Temp ?? 'Nothing';
echo $Demo."<br>";

$Temp = "Test Double Question Mark";
$Demo = $Temp ?? 'something';
echo $Demo;
?>

上面的程式碼將首先列印 nothing,因為 $Demo 的值為空,然後它列印字串 Test Double Question Mark,因為第一個運算元是 not null

輸出:

Nothing
Test Double Question Mark 

在 PHP 中的表單值上使用雙問號

我們可以在表單值上使用 Null Coalescing 運算子,因此如果沒有插入任何值,它可以列印其他內容。參見示例:

<!DOCTYPE HTML>
<html>
<body>
<form action="test.php" method="post">
Test Value 1: <input type="text" name="test1"><br>
Test Value 2: <input type="text" name="test2"><br>
<input type="submit">
</form>
</body>
</html>

此 HTML 程式碼將要求你輸入值,這些值將列印在下面給出的 test.php 上。

<?php
echo $_POST["test1"] ?? $_POST["test2"] ?? "Please enter a test value"; 
?>

該程式碼將列印它從表單中獲取的第一個非 Null 值,如果它沒有得到任何值,它將列印輸出:

Please enter a test value
作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相關文章 - PHP Operator