Definition:
isset — Determine if a variable is set and is not NULL
empty — Determine whether a variable is empty
用以下方法检查一个表单域是否填写并且不是空格:
if(isset($_POST[myField]) && $_POST[myField] != "") {
Do my PHP code
}
更好的方法
(
- "" (an empty string)
- 0 (0 as an integer)
- "0" (0 as a string)
- NULL
- FALSE
- array() (an empty array)
- var $var; (a variable declared, but without a value in a class)以上变量都被认为是empty
):
if(!empty($_POST[myField])) {
Do my PHP code
}
以下代码帮助更好的理解isset() and empty()
<?php
if (isset($var1)) echo '<p>var1 isset';
else echo '<p>var1 is not set';
if (empty($var1)) echo '<br>var1 is empty';
else echo '<br>var1 is not empty';
$var2 = '';
if (isset($var2)) echo '<p>var2 isset';
else echo '<p>var2 is not set';
if (empty($var2)) echo '<br>var2 is empty';
else echo '<br>var2 is not empty';
$var3 = 'something';
if (isset($var3)) echo '<p>var3 isset';
else echo '<p>var3 is not set';
if (empty($var3)) echo '<br>var3 is empty';
else echo '<br>var3 is not empty';
?>
本文介绍如何使用PHP内置函数isset()和empty()来有效检查变量的状态。通过实例演示了如何判断表单字段是否已填写且非空,以及如何更优雅地进行变量为空的判断。
1万+

被折叠的 条评论
为什么被折叠?



