PHP

[ Solved – 6 Answers ] PHP: How to use array_filter() to filter array keys?

How to use array_filter() to filter array keys? The callback function in array_filter() only passes in the array's values,
  • The callback function in array_filter() only passes in the array’s values, not the keys.

If I have:

Php code
$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:

Php Code
$my_array = array("foo" => 1);

  • 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:
Php Code
$my_array = ['foo' => 1, 'hello' => 'world'];
$allowed  = ['foo', 'bar'];
$filtered = array_filter(
    $my_array,
    function ($key) use ($allowed) {
        return in_array($key, $allowed);
    },
    ARRAY_FILTER_USE_KEY
);
  • 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:

Php Code
$my_array = ['foo' => 1, 'bar' => 'baz', 'hello' => 'wld'];
$allowed  = ['foo' => true, 'bar' => true, 'hello' => 'world'];
$filtered = array_filter(
    $my_array,
    function ($val, $key) use ($allowed) { // N.b. $val, $key not $key, $val
        return isset($allowed[$key]) && (
            $allowed[$key] === true || $allowed[$key] === $val
        );
    },
    ARRAY_FILTER_USE_BOTH
); // ['foo' => 1, 'bar' => 'baz']

  • With array_intersect_key and array_flip:
Php Code
var_dump(array_intersect_key($my_array, array_flip($allowed)));
array(1) {
  ["foo"]=>
  int(1)
}

  • we use a more complex array_filter on the keys.

Similar method:

Php Code
// Filter out array elements with keys shorter than 4 characters
$a = array(
  0      => "val 0", 
  "one"  => "val one", 
  "two"  => "val two", 
  "three"=> "val three", 
  "four" => "val four", 
  "five" => "val five", 
  "6"    => "val 6"
); 
$f = array_filter(array_keys($a), function ($k){ return strlen($k)>=4; }); 
$b = array_intersect_key($a, array_flip($f));
print_r($b);

Outputs :

Array

(

[three] => val three

[four] => val four

[five] => val five

)

  • Here is a more flexible solution using a closure:
Php Code
$my_array = array("foo" => 1, "hello" => "world");
$allowed = array("foo", "bar");
$result = array_flip(array_filter(array_flip($my_array), function ($key) use ($allowed)
{
    return in_array($key, $allowed);
}));
var_dump($result);

Outputs:

array(1) {

‘foo’ =>

int(1)

}

So in the function, you can do other specific tests.

  • Here’s a less flexible alternative using unset():
Php Code
$array = array(
    1 => 'one',
    2 => 'two',
    3 => 'three'
);
$disallowed = array(1,3);
foreach($disallowed as $key){
    unset($array[$key]);
}

The result of print_r($array) being:

Array
(
[2] => 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.

For example:

Php Code
$filtered = from($array)
    ->where(function ($v, $k) use ($allowed) {
        return in_array($k, $allowed);
    })
    ->toArray();

(The where function returns an iterator, so if you only need to iterate with foreach over the resulting sequence once, ->toArray() can be removed.)

About the author

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment