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);
array filter function from php:
$array - It is the input array
$callback_function - The callback function to use, If the callback function returns true, the current value from array is returned into the result array.
$flag - It is optional parameter, it will determine what arguments are sent to callback function. If this parameter empty then callback function will take array values as argument. If you want to send array key as argument then use $flag as ARRAY_FILTER_USE_KEY. If you want to send both keys and values you should use $flag as ARRAY_FILTER_USE_BOTH .
For Example : Consider simple array
If you want to filter array based on the array key, We need to use ARRAY_FILTER_USE_KEY as third parameter of array function array_filter.
If you want to filter array based on the array key and array value, We need to use ARRAY_FILTER_USE_BOTH as third parameter of array function array_filter.
Sample Callback functions:
It will output
PHP 5.6 introduced a third parameter to
array_filter()
,flag
, that you can set toARRAY_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: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. For example:(The
where
function returns an iterator, so if you only need to iterate withforeach
over the resulting sequence once,->toArray()
can be removed.)* developed by me
Here is a more flexible solution using a closure:
Outputs:
So in the function, you can do other specific tests.
With
array_intersect_key
andarray_flip
: