Filter associative array based on array key in PHP

PHP has so many built in function to work with array. In this tutorial I would present to you how to filter an associative array based on array keys. For example, you have an associative array [cci]$groups[/cci]:

$groups = array(
    'a' => 'book',
    'b' => 'pencil',
    'c' => 'pen'
);

And array of keys:

$keys = array('a', 'b');

Now, how to get sub array of [cci]$groups[/cci] which key contained in [cci]$keys[/cci]? Our goal is to create new associative array like this:

$news = array(
    'a' => 'book',
    'b' => 'pencil'
);

Every keys in array [cci]$news[/cci] contained in [cci]$keys[/cci]. Here the way to do that:

$news = array();

foreach($groups as $k=>$v){
    if(in_array($k, $keys)){
        $news[$k]  = $v;
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top