1

Given:

$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):

['xyz','456']

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:

array_values(array_intersect_key($info,array_flip($keys)));
Robert
  • 629
  • 7
  • 8
  • `['abc','123']` != `['xyz','456']`, so which is it, do you want the keys or the values? – Lawrence Cherone Aug 28 '17 at 02:40
  • 1
    `array_values()` for values `array_keys()` for keys. – Lawrence Cherone Aug 28 '17 at 02:41
  • https://stackoverflow.com/questions/4260086/php-how-to-use-array-filter-to-filter-array-keys – sumit Aug 28 '17 at 03:05
  • @LawrenceCherone I just wanted the values; I didn't mention ['abc','123'] in "what the best way to get" part. I will use array_values() like this, thank you array_values(array_intersect_key($info,array_flip($keys))); – Robert Aug 28 '17 at 03:47

1 Answers1

1

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

$out=array_intersect_key($info,array_flip($keys));

print_r($out);

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

OR

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

print_r($out);

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

  • Thank you. I will take the Array ( [abc] => xyz [123] => 456 ) output and apply array_values() to it! – Robert Aug 28 '17 at 03:50