正在读取数据,页面载入中,请稍后...

PHP中检查数组是否存在元素的方法

PHP数组是否存在元素的判断方法是什么?

方法1:使用 === 检查数组是否为空

// 检查数组是否为空
$arr = array(1,2,3);
if($arr===[]) {
	echo "数组中不存在元素";
} else {
	echo "数组中存在元素";
}

方法2:使用count() 检查数组是否为空

// 检查数组是否为空
$arr = array(1,2,3);
if(count($arr)) {
	echo "数组中存在元素";
} else {
	echo "数组中不存在元素";
}

方法3:使用sizeof() 检查数组是否为空

// 检查数组是否为空
$arr = array(1,2,3);
if(sizeof($arr)) {
	echo "数组中存在元素";
} else {
	echo "数组中不存在元素";
}

方法4:使用in_array()函数

$sites = array("Google", "phpcn", "Taobao", "Facebook");
if (in_array("phpcn", $sites)) {
	echo "存在指定值";
} else {
	echo "不存在指定值";
}

方法5:使用array_search()函数

$sites = array("Google", "phpcn", "Taobao", "Facebook");
if (array_search("red", $sites)) {
	echo "存在指定值";
} else {
	echo "不存在指定值";
}

以上五种方法均可判断数据是否存在元素。

本文结束