在 PHP 中檢查 Not Null 和空字串的語法
Habdul Hazeez
2023年1月30日
本文教你如何在 PHP 中檢查非 null 和空字串。我們將使用 PHP empty()
和 is_null()
函式以及否定運算子。
在 PHP 中使用 is_null()
檢查 Not Null
PHP is_null
函式將檢查變數是否為空。同時,你可以使用否定運算子附加它,它會檢查變數是否不為空。
在 PHP 中,否定運算子是感嘆號 (!
)。我們在下面給出一個例子,我們檢查一個字串是否不為空。
<?php
// Define a simple string
$sample_string = "I am a string";
// Check if it's not null. We use PHP is_null
// function, but we've added the negation
// sign before it.
if (!is_null($sample_string)) {
echo "Your variable <b>" . $sample_string . "</b> is not null.";
} else {
echo "Your variable is null.";
}
?>
輸出:
Your variable <b>I am a string</b> is not null.
在 PHP 中使用 empty()
檢查空字串
PHP empty()
函式允許你檢查空字串。此外,empty()
函式可以檢查 PHP 評估為空的其他值。
在下面的示例中,我們使用 empty()
函式來測試空字串以及其他值。
<?php
$empty_string = "";
$integer_zero = 0;
$decimal_zero = 0.0;
$string_zero = "0";
$null_keyword = NULL;
$boolean_false = FALSE;
$array_with_no_data = [];
$uninitialized_variable;
if (empty($empty_string)) {
echo "This message means the argument to function empty() was an empty string. <br />";
}
if (empty($integer_zero)) {
echo $integer_zero . " is empty. <br />";
}
if (empty($decimal_zero)) {
echo number_format($decimal_zero, 1) . " is empty. <br />";
}
if (empty($string_zero)) {
echo $string_zero . " as a string is empty. <br />";
}
if (empty($null_keyword)) {
echo "NULL is empty. <br />";
}
if (empty($boolean_false)) {
echo"FALSE is empty. <br />";
}
if (empty($array_with_no_data)) {
echo "Your array is empty. <br />";
}
if (empty($uninitialized_variable)) {
echo "Yes, your uninitialized variable is empty.";
}
?>
輸出:
This message means the argument to function empty() was an empty string. <br />
0 is empty. <br />
0.0 is empty. <br />
0 as a string is empty. <br />
NULL is empty. <br />
FALSE is empty. <br />
Your array is empty. <br />
Yes, your uninitialized variable is empty.
作者: Habdul Hazeez
Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.
LinkedIn