Robert Robert - 9 months ago 37
PHP Question

How to get a subset of an array's values in PHP?


$info = ['abc'=>'xyz', '123'=>'456', 'vowels'=>'aeiou']; //complete data array
$keys = ['abc','123']; //list of keys I'm interested in getting the VALUES for

What's the best way to get an array like this (no KEYS in it):


Currently, I have this, but feel there might be some other way with PHP's built-in array functions:

$result = [];

foreach ($keys as $key) {
$result[] = $info[$key];

return $result;

Other answers describe a 'pluck' type function, but those all return keys too... I only want the values.

Update: The answer seems to be a combination of two responses below:


Answer Source

Nothing particularly bad about your approach, but here are a couple of alternatives

$info = ['abc'=>'xyz', '123'=>'456', 'vowels'=>'aeiou'];  //complete data array
$keys = ['abc','123'];  //list of keys I'm interested in



Array ( [abc] => xyz [123] => 456 )


$out= array_map(function($x) use ($info) { return $info[$x]; }, $keys);


Array ( [0] => xyz [1] => 456 )

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download