PHP数组函数array_key_exists()的用法

admin 阅读:74 2024-03-05
array_key_exists

(PHP 4 >= 4.0.7, PHP 5)

array_key_exists — 检查给定的键名或索引是否存在于数组中

说明

bool array_key_exists ( mixed $key , array $search )

array_key_exists() 在给定的 key 存在于数组中时返回 TRUEkey 可以是任何能作为数组索引的值。array_key_exists() 也可用于对象。

参数

key

要检查的键。

search

一个数组,包含待检查的键。


返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例


Example #1 array_key_exists() 例子

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>


Example #2 array_key_exists() 与 isset() 的对比

isset() 对于数组中为 NULL 的值不会返回 TRUE,而 array_key_exists() 会。

<?php
$search_array = array('first' => null, 'second' => 4);

// returns false
isset($search_array['first']);

// returns true
array_key_exists('first', $search_array);
?>

注释

Note:

为了向下兼容,可以使用下列已废弃的别名: key_exists()


Note:

For backward compatibility reasons, array_key_exists() will also return TRUE if key is a property defined within an object given as search. This behaviour should not be relied upon, and care should be taken to ensure that search is an array.

To check whether a property exists in an object, use property_exists().


参见

isset() - 检测变量是否设置 array_keys() - 返回数组中所有的键名 in_array() - 检查数组中是否存在某个值 property_exists() - 检查对象或类是否具有该属性

声明

1、部分文章来源于网络,仅作为参考。
2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!