tags:

views:

34

answers:

2

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?

A: 

Nope. That's the most elegant.

Matt Williamson
A: 

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