Array_values ​​from multidimensional array

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 this can be easily done by iterating over an array and storing the values ​​in another array, but is there a shorter way, a built-in PHP function or something?

+3


source to share


4 answers


$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');

      



+10


source


Since 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
)

      

+9


source


You can do:

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

      

Anyone reading your code after this should know that the reset side effect returns the first value in the array. It may or may not be more readable - and it has the disadvantage that it doesn't work unless the array has a zero-indexed entry:

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

      

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

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

$baz = array_map('array_first', $arr);

      

+6


source


No, you cannot do this without using some kind of loop ...

To do this, just use a loop and store the values ​​in a new array, or use a callback function to get your values.

+1


source







All Articles