PHP: How to use array_filter() to filter array keys?

maček picture maček · Nov 23, 2010 · Viewed 284.6k times · Source

The callback function in array_filter() only passes in the array's values, not the keys.

If I have:

$my_array = array("foo" => 1, "hello" => "world");

$allowed = array("foo", "bar");

What's the best way to delete all keys in $my_array that are not in the $allowed array?

Desired output:

$my_array = array("foo" => 1);

Answer

Vincent Savard picture Vincent Savard · Nov 23, 2010

With array_intersect_key and array_flip:

var_dump(array_intersect_key($my_array, array_flip($allowed)));

array(1) {
  ["foo"]=>
  int(1)
}