isset() and empty() in PHP

来源:互联网 发布:免费视频转换软件 编辑:程序博客网 时间:2024/06/01 21:05

Definition:

issetDetermine if a variable is set and is not NULL

emptyDetermine 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';
?>