Search code examples
phparraysarray-column

Get array values from specific column in a 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 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?


Solution

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