如何检查数组元素是否存在? [英] How to check if an array element exists?

查看:92
本文介绍了如何检查数组元素是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:我正在检查是否存在像这样的数组元素:

Example: I'm checking for the existence of an array element like this:

if (!self::$instances[$instanceKey]) {
    $instances[$instanceKey] = $theInstance;
}

但是,我不断收到此错误:

However, I keep getting this error:

Notice: Undefined index: test in /Applications/MAMP/htdocs/mysite/MyClass.php on line 16

当然,我第一次想要实例时,$ instances将不知道密钥.我想我对可用实例的检查是错误的?

Of course, the first time I want an instance, $instances will not know the key. I guess my check for available instance is wrong?

推荐答案

您可以使用以下语言结构之一 isset 或函数 array_key_exists .

You can use either the language construct isset, or the function array_key_exists.

isset应该更快一些(因为它不是函数),但是如果元素存在并且值为NULL,则返回false.

isset should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL.


例如,考虑以下数组:


For example, considering this array :

$a = array(
    123 => 'glop', 
    456 => null, 
);

这三个测试,都依赖于isset:

And those three tests, relying on isset :

var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));

第一个会得到您(该元素存在,并且不为空):

boolean true

第二个会得到(该元素存在,但为空):

boolean false

最后一个会得到(该元素不存在):

boolean false


另一方面,像这样使用array_key_exists:


On the other hand, using array_key_exists like this :

var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));

您将获得这些输出:

boolean true
boolean true
boolean false

因为在前两种情况下,该元素存在-即使在第二种情况下为null.而且,当然,在第三种情况下,它不存在.

Because, in the two first cases, the element exists -- even if it's null in the second case. And, of course, in the third case, it doesn't exist.


对于像您这样的情况,我通常使用isset,考虑到我永远不会在第二种情况下...但是,现在选择使用哪个是您的决定;-)


For situations such as yours, I generally use isset, considering I'm never in the second case... But choosing which one to use is now up to you ;-)

例如,您的代码可能会变成这样:

For instance, your code could become something like this :

if (!isset(self::$instances[$instanceKey])) {
    $instances[$instanceKey] = $theInstance;
}

这篇关于如何检查数组元素是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆