为什么要在PHP中同时检查isset()和!empty()函数?

2021年4月18日19:22:35 发表评论 776 次浏览

isset()函数

isset()函数PHP中的内置函数, 它检查是否设置了变量, 并且该变量不是NULL。此函数还检查声明的变量, 数组或数组键是否具有空值, 如果存在, 则isset()返回false, 在所有其他可能情况下返回true。

语法如下:

bool isset( $var, mixed )

参数:此函数接受多个参数。该函数的第一个参数是$ var。此参数用于存储变量的值。

例子:

<?php
  
//PHP program to illustrate 
//isset() function
$num = '0' ;
  
if ( isset( $num ) ) {
     print_r( " $num is set with isset function <br>" );
}
  
//Declare an empty array 
$array = array (); 
    
//Use isset function 
echo isset( $array [ 'geeks' ]) ? 
'array is set.' :  'array is not set.' ; 
?>

输出如下:

0 is set with isset function array is not set.

empty()函数

empty()函数是一种用于确定给定变量为空还是NULL的语言构造。 !empty()函数是empty()函数的取反或补码。 empty()函数与!isset()函数相当, 而!empty()函数与isset()函数相等。

例子:

<?php
  
//PHP program to illustrate
//empty() function
  
$temp = 0;
  
//It returns true because 
//$temp is empty
if ( empty ( $temp )) {
     echo $temp . ' is considered empty' ;
}
  
echo "\n" ;
  
//It returns true since $new exist
$new = 1;
if (! empty ( $new )) {
     echo $new . ' is considered set' ;
}
?>

输出如下:

0 is considered empty
1 is considered set

同时检查两个功能的原因:

isset()和!empty()函数相似, 并且两者将返回相同的结果。但是唯一的区别是!empty()函数在变量不存在时不会生成任何警告或电子通知。使用任何一个功能就足够了。通过将两个函数合并到程序中, 将导致时间流逝和不必要的内存使用。

例子:

<?php
  
//PHP function to demonstrate isset()
//and !empty() function
  
//Inintialize a variable
$num = '0' ;
  
//Check isset() function
if ( isset ( $num ) ) {
     print_r( $num . " is set with isset function" );
}
  
//Display new line
echo "\n" ;
  
//Inintialize a variable
$num = 1;
  
//Check the !empty() function
if ( ! empty ( $num ) ) {
     print_r( $num . " is set with !empty function" );
}

输出如下:

0 is set with isset function
1 is set with !empty function

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: