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]:
1 2 3 4 5 | $groups = array ( 'a' => 'book' , 'b' => 'pencil' , 'c' => 'pen' ); |
And array of keys:
1 | $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:
1 2 3 4 | $news = array ( 'a' => 'book' , 'b' => 'pencil' ); |
Every keys in array [cci]$news[/cci] contained in [cci]$keys[/cci]. Here the way to do that:
1 2 3 4 5 6 7 | $news = array (); foreach ( $groups as $k => $v ){ if (in_array( $k , $keys )){ $news [ $k ] = $v ; } } |