11

According to the PHP Manual, calling array_map with a NULL callback causes it to perform a "zip" function, creating an array of arrays of parallel elements from the given arrays.

For example:

array_map(NULL,array(1,2,3),array('a','b','c'));

yields

array(array(1,'a'),array(2,'b'),array(3,'c'))

This is also equivalent to transposing the array

array(array(1,2,3),array('a','b','c'))

Right now, it appears this is the closest way (using built-in functions) you can transpose an array, except that array_map takes a list of arrays, not an array of arrays.

In some code I am working on, I need to transpose an array of arrays, not a list of arrays, so I made this work-around:

call_user_func_array('array_map',array_merge(array(NULL),$array_of_arrays))

However, this feels very dirty and clumsy.

And so I ask:
Is there a better way to transpose a 2D array with PHP, aside from a custom implementation?

Austin Hyde
  • 26,347
  • 28
  • 96
  • 129

3 Answers3

4

Update for PHP 5.6:

We can take advantage of PHP 5.6's "splat" operator to make this operation much, much cleaner with argument unpacking:

array_map(null, ...$array_of_arrays);

For example:

[1] boris> $arr2d = [ [1,2,3], ['a','b','c'] ];
// array(
//   0 => array(
//     0 => 1,
//     1 => 2,
//     2 => 3
//   ),
//   1 => array(
//     0 => 'a',
//     1 => 'b',
//     2 => 'c'
//   )
// )
[2] boris> array_map(null, ...$arr2d);
// array(
//   0 => array(
//     0 => 1,
//     1 => 'a'
//   ),
//   1 => array(
//     0 => 2,
//     1 => 'b'
//   ),
//   2 => array(
//     0 => 3,
//     1 => 'c'
//   )
// )
Austin Hyde
  • 26,347
  • 28
  • 96
  • 129
4

Nope. That's the most elegant.

Matt Williamson
  • 39,165
  • 10
  • 64
  • 72
1

If you really want to avoid the array_merge, use array_unshift to prepend the NULL to the $array_of_arrays instead:

array_unshift($array_of_arrays, NULL);
call_user_func_array('array_map', $array_of_arrays);

Of course it is not a one-liner anymore :P

Lukman
  • 18,462
  • 6
  • 56
  • 66
  • And it alters `$array_of_arrays` if I would want to use it later, so I would have to `array_shift($array_of_arrays)` afterwards... – Austin Hyde Aug 11 '10 at 15:56
  • @Austin Hyde: true. you can just make a copy of the array: `$array_of_arrays = $my_arrays_of_arrays` beforehand – user102008 Oct 30 '11 at 21:26