Extracting a subset of values from an associative array (php)

user58777 picture user58777 · Feb 20, 2009 · Viewed 7k times · Source

I want to do something seemingly very simple, but I can't find anything about it: simply extract a subset of an array similar to array_splice, but using keys to retrieve the values :

$data = array('personName' => 'John', 'personAge' => 99, 'personId' => 1,  
              /* many more data I don't need here ... */);

list($name, $age, $id) = array_splice_by_keys($data,
                          array('personName', 'personAge', 'personId');

If all else fails, isn't there a builtin function to filter an associative array by keys? For example:

$filteredArray = array__extract__keys__and__values($srcArray, $arrayOfWantedKeys);

// create a new array with ONLY those key => values I need
$wanted_values = array_extract_keys_and_values($data,
                  array('personName', 'personAge', 'personId');

echo $wanted_values['personName'];  

I guess the reason why I want to do the first one, is that I don't like to repeat associative array access all over my code, it would seem better optimized to copy the values that are used a lot (in a loop for example), into a local variable, plus it's much easier to type $name than $somearray['name'].

EDIT: Thanks, I guess for use with list, the solution would be

list($x, $y, $z) = array_values(array_intersect_key($array, array_flip($wantedKeys)));

Intesresting use of array_flip!

Answer

Tom Haigh picture Tom Haigh · Feb 20, 2009

This is essentially the same as SilentGhost's answer but this might be easier, and probably a little slower.

array_intersect_key($array, array_flip($wantedKeys));