views:

633

answers:

2

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!

+3  A: 

in php version >= 5.1.0 you could use array_intersect_key:

$data = array('personName' => 'John', 'personAge' => 99, 'personId' => 1,  
          'test' => 23);
$ex = array('personName'=>0, 'personAge'=>0, 'personId'=>0);
var_dump(array_intersect_key($data, $ex));

values in $ex don't matter, they just have to be present.

SilentGhost
+2  A: 

Pretty much the same as SilentGhost's answer but this might be easier and also slower

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