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

yipeiwu_com7年前PHP代码库

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

以上就是本次介绍的全部知识点,感谢大家对【宜配屋www.yipeiwu.com】的支持。

相关文章

php计算十二星座的函数代码

核心代码: 复制代码 代码如下: <?php /* * 计算星座的函数 string get_zodiac_sign(string month, string day) * 输入:...

PHP实现打包下载文件的方法示例

本文实例讲述了PHP实现打包下载文件的方法。分享给大家供大家参考,具体如下: /** * 下载文件 * @param $img * @return string */ public...

PHP开发中的错误收集,不定期更新。

Fatal error: Non-static method Conn::__construct() cannot be called statically in /file.php 没...

PHP多线程抓取网页实现代码

受限于php语言本身不支持多线程,所以开发爬虫程序效率并不高,这时候往往需 要借助Curl Multi Functions 它可以实现并发多线程的访问多个url地址。既然 Curl Mu...

PHP封装的数据库模型Model类完整示例【基于PDO】

本文实例讲述了PHP封装的数据库模型Model类。分享给大家供大家参考,具体如下: <?php //引入配置文件 include "../Config/...