php 如何检查数组元素是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1966169/
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-25 04:29:08  来源:igfitidea点击:

How to check if an array element exists?

php

提问by openfrog

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

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

当然,第一次想要实例时,$instances 是不会知道key的。我猜我对可用实例的检查是错误的?

回答by Pascal MARTIN

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

您可以使用语言结构isset或函数array_key_exists

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

isset应该快一点(因为它不是函数),但如果元素存在并具有 value ,则将返回 false NULL


For example, considering this array :


例如,考虑这个数组:

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

And those three tests, relying on isset:

而这三个测试,依赖于isset

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

The first one will get you (the element exists, and is not null):

第一个会让你(元素存在,并且不为空)

boolean true

While the second one will get you (the element exists, but is null):

虽然第二个会得到你(元素存在,但为空)

boolean false

And the last one will get you (the element doesn't exist):

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

boolean false


On the other hand, using array_key_existslike this :


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

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

You'd get those outputs :

你会得到这些输出:

boolean true
boolean true
boolean false

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.

因为,在前两种情况下,元素存在——即使在第二种情况下它为空。而且,当然,在第三种情况下,它不存在。


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 ;-)


对于像你这样的情况,我通常使用isset,考虑到我从来没有在第二种情况下......但是现在选择使用哪个取决于你;-)

For instance, your code could become something like this :

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

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

回答by LazNiko

array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.

与isset() 相比,array_key_exists() 慢。这两者的组合(见下面的代码)会有所帮助。

It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)

它利用isset()的性能优势,同时保持正确的检查结果(即即使数组元素为NULL也返回TRUE)

if (isset($a['element']) || array_key_exists('element', $a)) {
       //the element exists in the array. write your code here.
}

The benchmarking comparison: (extracted from below blog posts).

基准比较:(摘自以下博客文章)。

array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms

See http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/and http://thinkofdev.com/php-isset-and-multi-dimentional-array/

请参阅 http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/http://thinkofdev.com/php-isset-and-multi-维度数组/

for detailed discussion.

进行详细讨论。

回答by missingfaktor

You can use the function array_key_existsto do that.

您可以使用该功能array_key_exists来做到这一点。

For example,

例如,

$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }

PS : Example taken from here.

PS:示例取自此处

回答by Sampson

You can use isset()for this very thing.

你可以用isset()这个东西。

$myArr = array("Name" => "Jonathan");
print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ;

回答by Sampson

According to the php manual you can do this in two ways. It depends what you need to check.

根据 php 手册,您可以通过两种方式执行此操作。这取决于你需要检查什么。

If you want to check if the given key or index exists in the array use array_key_exists

如果要检查数组中是否存在给定的键或索引,请使用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";
 }
?>

If you want to check if a value exists in an array use in_array

如果要检查数组中是否存在值,请使用in_array

 <?php
 $os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
?>

回答by Rich

You want to use the array_key_exists function.

您想使用 array_key_exists 函数。

回答by Peter

A little anecdote to illustrate the use of array_key_exists.

一个小故事来说明array_key_exists.

// A programmer walked through the parking lot in search of his car
// When he neared it, he reached for his pocket to grab his array of keys
$keyChain = array(
    'office-door' => unlockOffice(),
    'home-key' => unlockSmallApartment(),
    'wifes-mercedes' => unusedKeyAfterDivorce(),
    'safety-deposit-box' => uselessKeyForEmptyBox(),
    'rusto-old-car' => unlockOldBarrel(),
);

// He tried and tried but couldn't find the right key for his car
// And so he wondered if he had the right key with him.
// To determine this he used array_key_exists
if (array_key_exists('rusty-old-car', $keyChain)) {
    print('Its on the chain.');
}

回答by Pradeep Kumar Prabaharan

You can also use array_keysfor number of occurrences

您还可以使用array_keys来表示出现次数

<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
 echo "Element exists in Array";
?>