Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php compare array keys, not values

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_array)) {
    echo "The 'first' element is in the array";
}
?>

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

like image 436
coffeemonitor Avatar asked Jan 19 '26 15:01

coffeemonitor


1 Answers

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))
like image 112
Matchu Avatar answered Jan 22 '26 03:01

Matchu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!