array_filter
Regardless of how I like Vincent's solution for Macek'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';
}