KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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!
Tags (comma-separated)
Save Edits
Cancel