10

The array looks like

$arr = array(

  array('a', 'b'),
  array('c', 'd'),
  array('e', 'f'),

)

And I want to get an array with values from the first column, like array('a', 'c', 'e')

I know it can easily be done by iterating the array and store the values in another array, but is there a shorter way, a built-in PHP function or something?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
thelolcat
  • 10,995
  • 21
  • 60
  • 102

4 Answers4

21

As of PHP 5.5 you can use array_column():

$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe'
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith'
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones'
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe'
    )
);

$lastNames = array_column($records, 'last_name', 'id');

print_r($lastNames);

Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)
John Conde
  • 217,595
  • 99
  • 455
  • 496
16
$arr = array(

  array('a', 'b'),
  array('c', 'd'),
  array('e', 'f'),

);

// You can make it look concise using array_map :)
$arr = array_map(function($x){ return $x[0]; }, $arr);

// $arr = array('a', 'c', 'e');
Paul
  • 139,544
  • 27
  • 275
  • 264
7

You could do:

$foo = array_map('reset', $arr);

Anyone reading your code after will need to know that a side effect of reset is returning the first value in an array. This may or may not be any more readable -- and it has the drawback of not working if the array does not have an entry indexed by zero:

$baz = array_map(function ($a) { return $a[0]; }, $arr);

If you want to be really clear and don't mind having a function lying around:

function array_first($a) {
    return reset($a);
}

$baz = array_map('array_first', $arr);
jmullan
  • 71
  • 1
  • 1
    `reset` returns the *first* element, not the element indexed by `0`. It works either way. – deceze Mar 14 '12 at 02:08
  • I lost the string keys, it was replaced by integer, this is helpful for flattening array index by numbers but not index by string keys – bdalina Mar 13 '19 at 04:21
0

No you can't do this without using any loop ...

In order to do it, just use a loop and store the values in a new array or use a callback function in order to get your values.

ChapMic
  • 26,954
  • 1
  • 21
  • 20
  • Compared to other answers on this page and the countless answers on all of the duplicate pages on Stack Overflow on this topic, this "hint" of an answer doesn't really have much to offer researchers. It seems safe to remove in my opinion. – mickmackusa May 19 '22 at 04:23