2016年10月17日 星期一

PHP: How to use array_filter() to filter by array 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);

Solution : 
If you're using PHP >= 5.6 you can now set a flag to filter on array key instead of array value:
$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. $allowedcould contain regex patterns instead of plain strings.


from : http://stackoverflow.com/questions/4260086/php-how-to-use-array-filter-to-filter-array-keys

沒有留言:

wibiya widget