PHP array_filter, how to get the key in callback?
From the documentation:PHP 5.6.0 Added optional flag parameter and constants ARRAY_FILTER_USE_KEY
and ARRAY_FILTER_USE_BOTH
In a previous comment you outlined you're actually looking for something like this:
foreach ($t as $k => $v) if (!array_key_exists($k, $valid)) unset($t[$k])
So actually to remove all values from array $t
that do not have a key in array $valid
.
The PHP function for that is called array_intersect_key
. The intersection is equal to the filtered result:
$filtered = array_intersect_key($t, $valid);
There's no way to let the callback of array_filter
access the element's key, nor is there a similar function that does what you want.
However, you can write your own function for this, like the one below:
function arrayfilter(array $array, callable $callback = null) { if ($callback == null) { $callback = function($key, $val) { return (bool) $val; }; } $return = array(); foreach ($array as $key => $val) { if ($callback($key, $val)) { $return[$key] = $val; } } return $return;}$test_array = array('foo', 'a' => 'the a', 'b' => 'the b', 11 => 1101, '', null, false, 0);$array = arrayfilter($test_array, function($key, $val) { return is_string($key);});print_r($array);/*Array( [a] => the a [b] => the b)*/$array = arrayfilter($test_array);print_r($array);/*Array( [0] => foo [a] => the a [b] => the b [11] => 1101)*/