2

如 php.net 所述,我已成功使用 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";
}
?>

但是,取出值,它不起作用。

<?php
$search_array = array('first', 'second');
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

不确定如何仅通过键比较 2 个数组。

4

5 回答 5

12

The first example is an associative array: keys with values assigned. The second example is just a prettier way of saying:

array(0 => 'first', 1 => 'second')

For the second, you would need to use in_array. You shouldn't check for the presence of a key, which array_key_exists does, but rather the presence of a value, which in_array does.

if(in_array('first', $array))
于 2010-05-26T22:23:58.553 回答
5

在 PHP 中,数组中的每个元素都有两部分:

除非您手动说出要附加到每个值的键,否则 PHP 会为每个元素提供一个数字索引,从 0 开始,以 1 递增。

所以两者的区别

array('first','second')

array('first'=>1,'second'=>4)

是第一个没有用户定义的键。(它实际上有键 0 和 1)

如果你要先做print_r(),它会说类似

Array {
    [0] => "first",
    [1] => "second"
}

而第二个看起来像

Array {
    ["first"]  => 1,
    ["second"] => 2
}

因此,要检查“first”是否存在,您可以使用

array_key_exists('first',$search_array);

要检查“first”是否存在,您可以使用

in_array('first',$search_array);
于 2010-05-26T22:29:25.747 回答
0

in the second example, you didn't assign array keys - you just set up a basic "list" of objects

use in_array("first", $search_array); to check if a value is in a regular array

于 2010-05-26T22:21:35.343 回答
0

In your second example the keys are numeric your $search_array actually looks like this:

array(0=>'first', 1=>'second');

so they key 'first' doesnt exist, the value 'first' does. so

in_array('first', $search_array);

is the function you would want to use.

于 2010-05-26T22:23:17.367 回答
0

在 PHP 中,如果您没有为数组元素提供键,它们将采用默认键值。在这里,您的数组将在内部如下所示

 $search_array = array(0=>'first', 1=>'second');

无论如何,您仍然可以使用下面的 array_flip 函数来解决这个问题。

$search_array = array('first', 'second');
if (array_key_exists('first', array_flip($search_array))) {
    echo "The 'first' element is in the array";
}
于 2015-08-20T08:55:36.747 回答