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