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]:

[sourcecode lang=”php”]
$groups = array(
‘a’ => ‘book’,
‘b’ => ‘pencil’,
‘c’ => ‘pen’
);
[/sourcecode]

And array of keys:

[sourcecode lang=”php”]
$keys = array(‘a’, ‘b’);
[/sourcecode]

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:

[sourcecode lang=”php”]
$news = array(
‘a’ => ‘book’,
‘b’ => ‘pencil’
);
[/sourcecode]

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

[sourcecode lang=”php”]
$news = array();

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


0 Comments

Leave a Reply

Avatar placeholder