开发者

php compare array keys, not values

开发者 https://www.devze.com 2022-12-31 23:46 出处:网络
I am successfully using the array_key_exists(), as described by php.net Example: <?php $search_array = array(\'first\' => 1, \'second\' => 4);

I am successfully using the array_key_exists(), as described by php.net

Example:

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

But, take out the values, and it doesn't work.

<?php
$search_array = array('first', 'second');
if (array_key_exists('first', $search_arr开发者_高级运维ay)) {
    echo "The 'first' element is in the array";
}
?>

Not sure how to only compare 2 arrays by their keys only.


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


In PHP, each element in a array has two parts: the key and the value.

Unless you manually say what keys you want attached to each value, PHP gives each element a numerical index starting at 0, incrementing by 1.

So the difference between

array('first','second')

and

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

is that the first doesn't have user-defined keys. (It actually has the keys 0 and 1)

If you were to do print_r() on the first, it would say something like

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

whereas the second would look like

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

So, to check if the key "first" exists, you would use

array_key_exists('first',$search_array);

to check if the the value "first" exists, you would use

in_array('first',$search_array);


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


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.


In PHP, if you are not giving key to array element they take default key value.Here you arrray will be internally as bellow

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

Anyway you can still fix this problem by using the array_flip function as below.

$search_array = array('first', 'second');
if (array_key_exists('first', array_flip($search_array))) {
    echo "The 'first' element is in the array";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消