在 PHP 中检查 Not Null 和空字符串的语法
Habdul Hazeez
2023年1月30日
2022年7月18日
本文教你如何在 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.
Author: 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