- The callback function in array_filter() only passes in the array’s values, not the keys.
If I have:
- What’s the best way to delete all keys in $my_array that are not in the $allowed array?
- PHP 5.6 introduced a third parameter to array_filter(), flag, that you can set to ARRAY_FILTER_USE_KEY to filter by key instead of value:
- Clearly this isn’t as elegant as array_intersect_key($my_array, array_flip($allowed)), but it does offer the additional flexibility of performing an arbitrary test against the key, e.g. $allowed could contain regex patterns instead of plain strings.
- You can also use ARRAY_FILTER_USE_BOTH to have both the value and the key passed to your filter function.
Here’s a contrived example based upon the first, but note that I’d not recommend encoding filtering rules using $allowed this way:
- With array_intersect_key and array_flip:
- we use a more complex array_filter on the keys.
([three] => val three [four] => val four [five] => val five
- Here is a more flexible solution using a closure:
So in the function, you can do other specific tests.
- Here’s a less flexible alternative using unset():
The result of print_r($array) being:
 => two
This is not applicable if you want to keep the filtered values for later use but tidier, if you’re certain that you don’t.
- Perhaps an overkill if you need it just once, but you can use YaLinqo library* to filter collections (and perform any other transformations).
- This library allows peforming SQL-like queries on objects with fluent syntax. Its where function accepts a calback with two arguments: a value and a key.
(The where function returns an iterator, so if you only need to iterate with foreach over the resulting sequence once, ->toArray() can be removed.)