什么更快更好地确定数组键是否存在于 PHP 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/700227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:33:58  来源:igfitidea点击:

What's quicker and better to determine if an array key exists in PHP?

phpperformance

提问by alex

Consider these 2 examples...

考虑这两个例子......

$key = 'jim';

// example 1
if (isset($array[$key])) {
    // ...
}

// example 2    
if (array_key_exists($key, $array)) {
    // ...
}

I'm interested in knowing if either of these are better. I've always used the first, but have seen a lot of people use the second example on this site.

我有兴趣知道这两者是否更好。我一直使用第一个,但在本网站上看到很多人使用第二个示例。

So, which is better? Faster? Clearer intent?

那么,哪个更好?快点?更清晰的意图?

回答by Richard Levasseur

isset()is faster, but it's not the same as array_key_exists().

isset()更快,但与array_key_exists().

array_key_exists()purely checks if the key exists, even if the value is NULL.

array_key_exists()纯粹检查键是否存在,即使值是NULL.

Whereas isset()will return falseif the key exist and value is NULL.

而 如果键存在且值为 ,isset()则将返回。falseNULL

回答by Populus

If you are interested in some tests I've done recently:

如果您对我最近所做的一些测试感兴趣:

https://stackoverflow.com/a/21759158/520857

https://stackoverflow.com/a/21759158/520857

Summary:

概括:

| Method Name                              | Run time             | Difference
=========================================================================================
| NonExistant::noCheckingTest()            | 0.86004090309143     | +18491.315775911%
| NonExistant::emptyTest()                 | 0.0046701431274414   | +0.95346080503016%
| NonExistant::isnullTest()                | 0.88424181938171     | +19014.461681183%
| NonExistant::issetTest()                 | 0.0046260356903076   | Fastest
| NonExistant::arrayKeyExistsTest()        | 1.9001779556274      | +209.73055713%

回答by CMS

Well, the main difference is that isset()will not return truefor array keys that correspond to a null value, while array_key_exists()does.

好吧,主要区别在于isset()不会返回true对应于空值的数组键,而array_key_exists()会。

Running a small benchmarkshows that isset()it's faster but it may not be entirely accurate.

运行一个小型基准测试表明isset()它更快,但它可能不完全准确。

回答by Xorifelse

I wanted to add my 2 cents on this question, since I was missing a middle way out.

我想在这个问题上加 2 美分,因为我错过了一个中间出路。

As already told isset()will evaluate the value of the key so it will return falseif that value is nullwhere array_key_exists()will only check if the key exists in the array.

如前所述,isset()将评估键的值,因此false如果该值位于nullwherearray_key_exists()将仅检查键是否存在于数组中,它将返回。



I've ran a simple benchmark using PHP 7, the results shown is the time it took to finish the iteration:

我使用 PHP 7 运行了一个简单的基准测试,显示的结果是完成迭代所需的时间:

$a = [null, true];

isset($a[0])                            # 0.3258841  - false
isset($a[1])                            # 0.28261614 - true
isset($a[2])                            # 0.26198816 - false

array_key_exists(0, $a)                 # 0.46202087 - true
array_key_exists(1, $a)                 # 0.43063688 - true
array_key_exists(2, $a)                 # 0.37593913 - false

isset($a[0]) || array_key_exists(0, $a) # 0.66342998 - true
isset($a[1]) || array_key_exists(1, $a) # 0.28389215 - true
isset($a[2]) || array_key_exists(2, $a) # 0.55677581 - false

array_key_isset(0, $a)                  # 1.17933798 - true
array_key_isset(1, $a)                  # 0.70253706 - true
array_key_isset(2, $a)                  # 1.01110005 - false

I've added the results from this custom function with this benchmark as well for completion:

我已将此自定义函数的结果添加到此基准测试中以供完成:

function array_key_isset($k, $a){
    return isset($a[$k]) || array_key_exists($k, $a);
}


As seen and already told isset()is fastest method but it can return false if the value is null. This could give unwanted results and usually one should use array_key_exists()if that's the case.

正如所见和已经告诉isset()是最快的方法,但如果值为null. 这可能会产生不需要的结果,array_key_exists()如果是这种情况,通常应该使用。

However there is a middle way out and that is using isset() || array_key_exists(). This code is generally using the faster function isset()and ifisset()returns false only thenuse array_key_exists()to validate. Shown in the table above, its just as fast as plainly calling isset().

但是,有一个中间出路,那就是使用isset() || array_key_exists(). 此代码通常使用更快的功能isset()如果isset()返回false使用array_key_exists()来验证。如上表所示,它与简单地调用isset().

Yes, it's a bit more to write and wrapping it in a function is slower but a lot easier. If you need this for performance, checking big data, etc write it out full, otherwise if its a 1 time usage that very minor overhead in function array_key_isset()is negligible.

是的,在函数中编写和包装它会更慢,但要容易得多。如果你需要这个来提高性能,检查大数据等,把它写满,否则如果它使用 1 次,那么非常小的功能开销array_key_isset()可以忽略不计。

回答by John

With Php 7 gives the possibility to use the Null Coalescing Operator.

Php 7 提供了使用Null Coalescing Operator的可能性。

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

空合并运算符 (??) 已被添加为语法糖,用于需要将三元与 isset() 结合使用的常见情况。如果存在且不为 NULL,则返回其第一个操作数;否则它返回它的第二个操作数。

So now you can assign a default value in case the value is null or if the key does not exist :

因此,现在您可以在值为 null 或键不存在的情况下分配默认值:

$var = $array[$key] ?? 'default value'

回答by Scott Evernden

there is a difference from php.netyou'll read:

php.net有所不同,您将阅读:

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.

对于与 NULL 值对应的数组键,isset() 不会返回 TRUE,而 array_key_exists() 会。

A very informal test shows array_key_exists()to be about 2.5 times slower than isset()

一个非常非正式的测试表明array_key_exists()isset()

回答by H A?d?μ

Combining isset()and is_null()give the best performance against other functions like: array_key_exists(), isset(), isset()+ array_key_exists(), is_null(), isset()+ is_null(), the only issue here is the function will not only return false if the key doesn't exist, but even the key exist and has a null value.

结合isset()is_null()针对其他函数提供最佳性能,例如:array_key_exists(), isset(), isset()+ array_key_exists(), is_null(), isset()+ is_null(),这里唯一的问题是该函数不仅在键不存在时返回 false,而且即使键存在并且具有空值。

Benchmark script:

基准脚本:

<?php
  $a = array('a' => 4, 'e' => null)

  $s = microtime(true); 
  for($i=0; $i<=100000; $i++) { 
    $t = (isset($a['a'])) && (is_null($a['a'])); //true 
    $t = (isset($a['f'])) && (is_null($a['f'])); //false
    $t = (isset($a['e'])) && (is_null($a['e']));; //false 
  } 

  $e = microtime(true); 
  echo 'isset() + is_null() : ' , ($e-$s)."<br><br>";
?>

Credit: http://www.zomeoff.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/

信用http: //www.zomeoff.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/

回答by Tomalak

As to "faster": Try it (my money is on array_key_exists(), but I can't try it right now).

至于“更快”:试试吧(我的钱在array_key_exists(),但我现在不能尝试)。

As to "clearer in the intent": array_key_exists()

至于“意图更明确”: array_key_exists()

回答by Mihai Limb??an

Obviously the second example is clearer in intent, there's no question about it. To figure out what example #1 does, you need to be familiar with PHP's variable initialization idiosyncracies - and then you'll find out that it functions differently for null values, and so on.

显然,第二个例子的意图更清楚,这是毫无疑问的。要弄清楚示例 #1 的作用,您需要熟悉 PHP 的变量初始化特性 - 然后您会发现它对 null 值的功能不同,等等。

As to which is faster - I don't intend to speculate - run either in a tight loop a few hundred thousand times on your PHP version and you'll find out :)

至于哪个更快——我不打算推​​测——在你的 PHP 版本上运行几十万次,你会发现:)

回答by Gator

Your code, isset($array[$i]) || $array[$i] === null, will return true in every case, even if the key does not exists (and yield a undefined index notice). For the best performance what you'd want is if (isset($array[$key]) || array_key_exists($key,$array)){doWhatIWant();}

您的代码isset($array[$i]) || $array[$i] === null在任何情况下都将返回 true,即使键不存在(并产生未定义的索引通知)。为了获得最佳性能,您想要的是if (isset($array[$key]) || array_key_exists($key,$array)){doWhatIWant();}