Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 462
Solace Avatar asked Aug 24 '14 13:08

Solace


People also ask

How can I find matching values in two arrays PHP?

The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

Which PHP functions compare arrays and return the differences?

The array_diff() function compares the values of two (or more) arrays, and returns the differences.

Which PHP function returns an array with the elements of two or more arrays in one array?

PHP | Merging two or more arrays using array_merge()

How do I compare arrays with other arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.


2 Answers

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.

like image 137
Michel Avatar answered Oct 07 '22 00:10

Michel


Update

Check out the answer from Michel: https://stackoverflow.com/a/30841097/2879722. It's a better and easier solution.


Original Answer

If I am understanding this correctly:

Returning a new array:

$array_new = [];
foreach($array_two as $key)
{
    if(array_key_exists($key, $array_one))
    {
        $array_new[$key] = $array_one[$key];
    }
}

Stripping from $array_one:

foreach($array_one as $key => $val)
{
    if(array_search($key, $array_two) === false)
    {
        unset($array_one[$key]);
    }
}
like image 32
Skarpi Steinthorsson Avatar answered Oct 07 '22 01:10

Skarpi Steinthorsson