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);
Starting from PHP 5.6, you can use the
ARRAY_FILTER_USE_KEY
flag inarray_filter
:Otherwise, you can use this function (from TestDummy):
And here is an augmented version of mine, which accepts a callback or directly the keys:
Last but not least, you may also use a simple
foreach
:If you are looking for a method to filter an array by a string occurring in keys, you can use:
The result of
print_r($mResult)
isAn adaption of this answer that supports regular expressions
Output
//Filter out array elements with keys shorter than 4 characters // By using Anonymous function with Closure...
$output = array_filter(array_keys($input), comparison(4));
print_r($output);
Here's a less flexible alternative using unset():
The result of
print_r($array)
being: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.
With this function you can filter a multidimensional array
I needed to do same, but with a more complex
array_filter
on the keys.Here's how I did it, using a similar method.
This outputs the result: