1

I have a PHP array as:

$array = [
    ['key' => 'foo', 'value' => 'fooVal'],
    ['key' => 'bar', 'value' => 'barVal'],
];

Is there an easy way of extracting the keys so that I have ['foo', 'bar'] or I must loop through $array?

  • Possible duplicate of [Is there a function to extract a 'column' from an array in PHP?](https://stackoverflow.com/questions/1494953/is-there-a-function-to-extract-a-column-from-an-array-in-php) – Nigel Ren Jun 10 '18 at 16:34

1 Answers1

1

You can use array_column to get values of a single column from an array

$array = [
    ['key' => 'foo', 'value' => 'fooVal'],
    ['key' => 'bar', 'value' => 'barVal'],
];

$result = array_column( $array , 'key' ); 

echo "<pre>";
print_r( $result );
echo "</pre>";

This will result to:

Array
(
    [0] => foo
    [1] => bar
)

Doc: array_column()

Eddie
  • 26,593
  • 6
  • 36
  • 58