PHP中empty,is_null,isset,array() 中的异同和功能

来源:互联网 发布:手机笑声软件 编辑:程序博客网 时间:2024/05/22 11:57

PHP中empty,is_null,isset,array() 中的异同和功能  


empty -- 检查一个变量是否为空
bool empty ( mixed var )

如果 var 是非空或非零的值,则 empty() 返回 FALSE 。换句话说,""0"0"NULLFALSEarray()var $var; 以及没有任何属性的对象都将被认为是空的,如果var 为空,则返回 TRUE 

empty() 与 isset() 的一个简单比较

  1. <?php  
  2. $var 0;   
  3. // 结果为 true,因为 $var 为空  
  4. if (empty($var))    
  5.     echo '$var is either or not set at all' 
  6.   
  7. // 结果为 false,因为 $var 已设置  
  8. if (!isset($var))  
  9.     echo '$var is not set at all' 
  10.  
  11. ?> 

empty()只检测变量,检测任何非变量的东西都将导致解析错误。换句话说,后边的语句将不会起作用: empty(addslashes($name))

isset -- 检测变量是否设置
bool isset ( mixed var [, mixed var [, ...]] )如果 var 存在则返回 TRUE , 否则返回 FALSE

如果已经使用 unset() 释放了一个变量之后,它将不再是isset() 。若使用 isset() 测试一个被设置成 NULL 的变量,将返回FALSE 。同时要注意的是一个 NULL 字节("\0" )并不等同于 PHP 的NULL 常数。


isset() 只能用于变量,因为传递任何其它参数都将造成解析错误。若想检测常量是否已设置,可使用defined() 函数。

  1. <?php  
  2. $var '' 
  3.   // 结果为 TRUE,所以后边的文本将被打印出来。  
  4. if (isset($var))  
  5.     print "This var is set set so will print." 
  6.   
  7. // 在后边的例子中,我们将使用 var_dump 输出 isset() 的返回值。   
  8. $a "test" 
  9. $b "anothertest" 
  10.   
  11. var_dump( isset($a);      // TRUE  
  12. var_dump( isset ($a$b); // TRUE  
  13.   
  14. unset ($a);  
  15.   
  16. var_dump( isset ($a);     // FALSE  
  17. var_dump( isset ($a$b); // FALSE  
  18.   
  19. $foo NULL;  
  20. var_dump( isset ($foo);   // FALSE  
  21.   
  22. ?>
 
对于数组中的元素也同样有效
  1. <?php  
  2.   
  3. $a array ('test' => 1, 'hello' => NULL);  
  4.   
  5. var_dump( isset ($a['test']) );            // TRUE  
  6. var_dump( isset ($a['foo']) );             // FALSE  
  7. var_dump( isset ($a['hello']) );           // FALSE  
  8.   
  9. // 键 'hello' 的值等于 NULL,所以被认为是未置值的。  
  10. // 如果想检测 NULL 键值,可以试试下边的方法。  
  11. var_dump( array_key_exists('hello'$a); // TRUE  
  12.   
  13. ?>  

is_null --  检测变量是否为NULL
bool is_null ( mixed var )
如果 varnull 则返回 TRUE ,否则返回FALSE

 

总结:
empty在变量为null,0,"",'0',array()返回true
isset在判断null时返回false
is_null只要是null返回true,否则返回false


理解了这些,这三个函数足以区别开来了.

Comparisons of $x with PHP functionsExpressiongettype()empty()is_null()isset()boolean :if($x) $x = “”;stringTRUEFALSETRUEFALSE $x = nullNULLTRUETRUEFALSEFALSE var $x;NULLTRUETRUEFALSEFALSE $x is undefinedNULLTRUETRUEFALSEFALSE $x = array();arrayTRUEFALSETRUEFALSE $x = false;booleanTRUEFALSETRUEFALSE $x = true;booleanFALSEFALSETRUETRUE $x = 1;integerFALSEFALSETRUETRUE $x = 42;integerFALSEFALSETRUETRUE $x = 0;integerTRUEFALSETRUEFALSE $x = -1;integerFALSEFALSETRUETRUE $x = “1″;stringFALSEFALSETRUETRUE $x = “0″;stringTRUEFALSETRUEFALSE $x = “-1″;stringFALSEFALSETRUETRUE $x = “php”;stringFALSEFALSETRUETRUE $x = “true”;stringFALSEFALSETRUETRUE $x = “false”;stringFALSEFALSETRUETRUE