PHP: How to compare keys in one array with values in another, and return matches?

Solace picture Solace · Aug 24, 2014 · Viewed 24.2k times · Source

I have the following two arrays:

$array_one = array('colorZero'=>'black', 'colorOne'=>'red', 'colorTwo'=>'green', 'colorThree'=>'blue', 'colorFour'=>'purple', 'colorFive'=>'golden');

$array_two = array('colorOne', 'colorTwo', 'colorThree');

I want an array from $array_one which only contains the key-value pairs whose keys are members of $array_two (either by making a new array or removing the rest of the elements from $array_one)

How can I do that?

I looked into array_diff and array_intersect, but they compare values with values, and not the values of one array with the keys of the other.

Answer

Michel picture Michel · Jun 15, 2015

As of PHP 5.1 there is array_intersect_key (manual).

Just flip the second array from key=>value to value=>key with array_flip() and then compare keys.

So to compare OP's arrays, this would do:

$result = array_intersect_key( $array_one , array_flip( $array_two ) );

No need for any looping the arrays at all.