您的位置 首页 php

为什么要在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.’;

?>

输出:

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’;

}

?>

输出:

is considered empty

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”);

}

输出:

is set with isset function

is set with !empty function

文章来源:智云一二三科技

文章标题:为什么要在PHP中同时检查isset()和!empty()函数

文章地址:https://www.zhihuclub.com/76710.shtml

关于作者: 智云科技

热门文章

网站地图