-3

I've the following two arrays:

// array1
Array (
 [key1] => value1,
 [key2] => value2,
 [key3] => value3,
 [key4] => value4,
 [key5] => value5
)

// array2
Array (
 [0] => key1,
 [1] => key3,
 [2] => key5
)

I would like to build a new array that includes only elements of array1 which keys are present in array2 as values, so to have the following:

// new array
Array (
 [key1] => value1,
 [key3] => value3,
 [key5] => value5
)

How can I make that (maybe using something like arrays intersection)?

Backo
  • 18,291
  • 27
  • 103
  • 170

2 Answers2

2

You can use array_intersect_key and array_flip. See this working demo.

$a = [
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
    'key4' => 'value4',
    'key5' => 'value5',
];

$b = ['key1', 'key3', 'key5'];

$c = array_intersect_key($a, array_flip($b));

print_r($c);
fubar
  • 16,918
  • 4
  • 37
  • 43
0

Reverse your $array2 so that the values become keys and vice versa. After that, use array_intersect_key to get common keys.

$reverseArray = array_flip($array2);
var_dump(array_intersect_key($array1, $reverseArray));

For more information, search this link.

david
  • 3,225
  • 9
  • 30
  • 43