首页 > 代码库 > PHP判断键值数组是否存在,使用empty或isset或array_key_exists

PHP判断键值数组是否存在,使用empty或isset或array_key_exists

<?php
$a = array(‘a‘=>1, ‘b‘=>0, ‘c‘=>NULL);
 
echo ‘a test by empty: ‘ , empty($a[‘a‘]) ? ‘not exist‘ : ‘exist‘, PHP_EOL;
echo ‘a test by isset: ‘ , isset($a[‘a‘]) ? ‘exist‘ : ‘not exist‘, PHP_EOL;
echo ‘a test by array_key_exists: ‘ , array_key_exists(‘a‘, $a) ? ‘exist‘ : ‘not exist‘, PHP_EOL, PHP_EOL;
 
echo ‘b test by empty: ‘ , empty($a[‘b‘]) ? ‘not exist‘ : ‘exist‘, PHP_EOL;
echo ‘b test by isset: ‘ , isset($a[‘b‘]) ? ‘exist‘ : ‘not exist‘, PHP_EOL;
echo ‘b test by array_key_exists: ‘ , array_key_exists(‘b‘, $a) ? ‘exist‘ : ‘not exist‘, PHP_EOL, PHP_EOL;
 
echo ‘c test by empty: ‘ , empty($a[‘c‘]) ? ‘not exist‘ : ‘exist‘, PHP_EOL;
echo ‘c test by isset: ‘ , isset($a[‘c‘]) ? ‘exist‘ : ‘not exist‘, PHP_EOL;
echo ‘c test by array_key_exists: ‘ , array_key_exists(‘c‘, $a) ? ‘exist‘ : ‘not exist‘, PHP_EOL, PHP_EOL;
?>
 

输出结果如下:

========================================================

a test by empty: exist

a test by isset: exist

a test by array_key_exists: exist

 

b test by empty: not exist

b test by isset: exist

b test by array_key_exists: exist

 

c test by empty: not exist

c test by isset: not exist

c test by array_key_exists: exist

========================================================

注意红色高亮部分

 

三种方式的语法区别

  • empty: 参数为0或为NULL时(如上面列子),empty均返回TRUE,
  • isset: 参数为NULL时,返回FALSE,0与NULL在PHP中是有区别的,isset(0)返回TRUE
  • array_key_exists: 纯粹的判断数组键值对是否存在,无论值是多少

所以,从准确性的角度来看,array_key_exists是最准确的!

 

声明:此博文是摘抄他人文章,旨在方便查找,学习使用,

PHP判断键值数组是否存在,使用empty或isset或array_key_exists