15

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.

Solace
  • 8,612
  • 22
  • 95
  • 183
  • 3
    array_diff() or array_intersect() combined with [array_keys()](http://www.php.net/manual/en/function.array-keys.php) – Mark Baker Aug 24 '14 at 13:42

3 Answers3

31

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.

Michel
  • 4,076
  • 4
  • 34
  • 52
6

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]);
    }
}
0

Tell me if it works:

for($i=0;$i<count($array_two);$i++){
  if($array_two[$i]==key($array_one)){
     $array_final[$array_two[$i]]=$array_one[$array_two[$i]];
     next($array_one);
  }
}
garry towel
  • 59
  • 1
  • 10
  • `$array_final` is a new array being created right? But I get `Notice: Undefined variable: array_final in C:\xampp\htdocs\testsNine.php on line 14` when I try to do `print_r($array_final);` after the loop. :s – Solace Aug 24 '14 at 14:17
  • sorry i forgot to declare it: $array_final = array(); – garry towel Aug 24 '14 at 14:36
  • I did try to declare it. That prints a blank array. You had also confused `count($array_two)` with `$array_two.length` from JS. That had also produced an error. But I understand the concept. SO thank you. – Solace Aug 24 '14 at 14:40