Home >php教程 >php手册 >PHP函数中isset和array_key_exists的差异

PHP函数中isset和array_key_exists的差异

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-13 11:41:131042browse

在判断某个 PHP 数组的索引值是否存在,一般会使用 <font face="NSimsun">isset</font><font face="NSimsun">array_key_exists</font> 两种方法。

isset($a['key'])
array_key_exists('key', $a)

<font face="NSimsun">array_key_exists</font> 确切地告诉你,数组是否存在某个键,而 <font face="NSimsun">isset</font> 则只是返回键值是否为 <font face="NSimsun">null</font> 的状态。也就是说,假设给定下面的数组:

$a = array('key1' => '123', 'key2' => null);

使用这两个方法判断键值存在情况,结果如下:

isset($a['key1']);             // true
array_key_exists('key1', $a);  // true

isset($a['key2']);             // false
array_key_exists('key2', $a);  // true

从 PHP 引擎本身来说,底层都是 C 语言的实现,<font face="NSimsun">array_key_exists</font><font face="NSimsun">isset</font> 应该都是很快的。如果运算次数上千次上万次,这种情况下 <font face="NSimsun">isset</font> 的性能应该更为显著。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn