华域联盟 PHP PHP中检查isset()和!empty()函数的必要性

PHP中检查isset()和!empty()函数的必要性

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

语法:

bool isset( $var, mixed )

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

例:

<?php 
  
$num = '0'; 
  
if( isset( $num ) ) { 
  print_r(" $num is set with isset function <br>"); 
} 
  
// 声明一个空数组 
$array = array(); 
   
echo isset($array['geeks']) ? 
'array is set.' : 'array is not set.'; 
?>

输出:

0 is set with isset function
array is not set.

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

例:

<?php 
  
  
$temp = 0; 
  
if (empty($temp)) { 
  echo $temp . ' is considered empty'; 
} 
  
echo "\n"; 
  
$new = 1; 
if (!empty($new)) { 
  echo $new . ' is considered set'; 
} 
?>

输出:

0 is considered empty
1 is considered set

检查两个函数的原因:

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

例:

<?php 
 
$num = '0'; 
  
if( isset ( $num ) ) { 
  print_r( $num . " is set with isset function"); 
} 
  
echo "\n"; 
  
$num = 1; 
  
if( !empty ( $num ) ) { 
  print_r($num . " is set with !empty function"); 
}

输出:

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

以上就是本次介绍的全部知识点,感谢大家对华域联盟的支持。

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » PHP中检查isset()和!empty()函数的必要性

转载请保留出处和原文链接:https://www.cnhackhy.com/53242.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部