php empty用法

笔记2024-03-236 人已阅来源:网络

PHP empty的使用方法
在PHP中,empty()函数是相对简单常用的函数之一,它的作用是判断一个变量是否为空。关于empty()函数的语法和参数,下面我将结合实例来详细说明。
语法
empty ( mixed $var ) : bool
参数
var - 需要检查的变量。
返回值
如果变量不存在或者值为false(包括空字符串、零和“false”),返回true,否则返回false。
实例
假设我们有一些变量例如:
$string = ''; // 空字符串
$integer = 0; // 0
$boolean = false; // false
$null = NULL; // NULL
$array_empty = array(); // 空数组
$array_not_empty =[1,2,3];// 非空数组
下面我们分别使用empty()函数来判断这些变量是否为空:

$p1 = '

'; $p2 = '

'; echo $p1 . 'Test empty with empty string.' . $p2; if (empty($string)) { echo $p1 . 'String is empty.' . $p2; } else { echo $p1 . 'String is not empty.' . $p2; } echo $p1 . 'Test empty with zero.' . $p2; if (empty($integer)) { echo $p1 . 'Integer is empty.' . $p2; } else { echo $p1 . 'Integer is not empty.' . $p2; } echo $p1 . 'Test empty with false.' . $p2; if (empty($boolean)) { echo $p1 . 'Boolean is empty.' . $p2; } else { echo $p1 . 'Boolean is not empty.' . $p2; } echo $p1 . 'Test empty with NULL.' . $p2; if (empty($null)) { echo $p1 . 'NULL is empty.' . $p2; } else { echo $p1 . 'NULL is not empty.' . $p2; } echo $p1 . 'Test empty with empty array.' . $p2; if (empty($array_empty)) { echo $p1 . 'Array is empty.' . $p2; } else { echo $p1 . 'Array is not empty.' . $p2; } echo $p1 . 'Test empty with not empty array.' . $p2; if (empty($array_not_empty)) { echo $p1 . 'Array is empty.' . $p2; } else { echo $p1 . 'Array is not empty.' . $p2; }

结果:

Test empty with empty string.

String is empty.

Test empty with zero.

Integer is empty.

Test empty with false.

Boolean is empty.

Test empty with NULL.

NULL is empty.

Test empty with empty array.

Array is empty.

Test empty with not empty array.

Array is not empty.

从以上结果可以看出,empty()函数的确可以用来判断变量是否为空,而且对于各种类型的变量都适用。
需要注意的是,空格字符串不会被认为是空的,所以empty()函数会把它识别为非空变量。
结论
empty()函数在判断变量是否为空的时候非常方便,它可以同时处理各种类型的变量。但是,由于empty()对于空格字符串不会识别为“空”,所以在判断变量是否为空时,建议使用更加准确的函数,例如is_null()等。