Returning array of given keys from an array

Votes : 3.3
1413
Simple one, I was just wondering if there is a clean and eloquent way of returning all values from an associative array that do match a given key(s)? Here's what I mean:
//source array
$source = array('key_1'=>'value_1','key_2'=>'value_2','key_3'=>'value_3','key_4'=>'value_4','key_5'=>'value_5');

// Required keys
$filter1 = array('key_1','key_2');
$filter2 = array('key_3','key_4','key_5');
I wish to get result as : Array( ['key_1'] => 'value_1', ['key_2'] =>'value_2' ) // First $filter1 array Array( ['key_3'] => 'value_3', ['key_4'] =>'value_4', ['key_5'] =>'value_5', ) // Second $filter_2 array

Your Answer

1 Answer

answered
This function compatible with any php version.
function array_filter($source,$filters){
    $return = array();
    foreach($filters as $filter){
         if(isset($source[$filter]))$return[$filter] = $source[$filter];
    }
    return $source;
}

array_filter($source,$filter1);

2 Answer

answered
array_flip function use to convert $filter1 & $filter2 array values to keys, then source values fill into generate new array keys by using array_intersect_key function

array_intersect_key( $source , array_flip( $filter1 ));   /*For first $filter1 array.*/

array_intersect_key( $source , array_flip( $filter2 )) ;

What is the codrate ?

codrate.com is a standard, fast cross browsing and highly versatile site. It is useful for many large number of Program Development Industries. So you can get support form Codrators , who are the codrate's joiners around world to help your program developments, You can answer other codrator's questions. Communicate with them. Share your knowledge with them. Do you have an interest in programming, So publish your articles about programming. It will help to maintain your professional co-profile. Actually codrate.com is not such as a regular web site. It will be gave new experience, best narrow cross-browser view, reduce processing time to receive browsing request, it's mean do not wasting your time to browsing codrate's web pages because it has been upgrade always modern coding ways. So, what do you waiting for ?. Try your own.

Copyright 2015 Pride - Company. Design by Esila