繁体   English   中英

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

[英]How to check if an array element exists?

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

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

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

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

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

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

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


例如,考虑以下数组:

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

而这三个测试,依赖于isset

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

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

boolean true

虽然第二个可以帮助您(该元素存在,但为null)

boolean false

最后一个会让你(该元素不存在)

boolean false


另一方面,像这样使用array_key_exists

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。 而且,当然,在第三种情况下,它不存在。


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

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

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

与isset()相比,array_key_exists()较慢。 结合使用这两种方法(请参见下面的代码)会有所帮助。

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

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

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

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

参见http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/http://thinkofdev.com/php-isset-and-multi-三维阵列/

进行详细讨论。

您可以使用函数array_key_exists做到这一点。

例如,

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

PS: 这里取了一个例子。

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

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

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

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

您可以为此使用isset()

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

您要使用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.');
}

您还可以将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";
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM