PHP: How to use array_filter() to filter array key

2019-01-01 05:58发布

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);

标签: php arrays
13条回答
君临天下
2楼-- · 2019-01-01 07:04

How to get the current key of an array when using array_filter

Regardless of how I like Vincent's solution for Maček's problem, it doesn't actually use array_filter. If you came here from a search engine you maybe where looking for something like this (PHP >= 5.3):

$array = ['apple' => 'red', 'pear' => 'green'];
reset($array); // Unimportant here, but make sure your array is reset

$apples = array_filter($array, function($color) use ($&array) {
  $key = key($array);
  next($array); // advance array pointer

  return key($array) === 'apple';
}

It passes the array you're filtering as a reference to the callback. As array_filter doesn't conventionally iterate over the array by increasing it's public internal pointer you have to advance it by yourself.

What's important here is that you need to make sure your array is reset, otherwise you might start right in the middle of it.

In PHP >= 5.4 you could make the callback even shorter:

$apples = array_filter($array, function($color) use ($&array) {
  return each($array)['key'] === 'apple';
}
查看更多
登录 后发表回答