Transpose an Array in PHP
How to transpose arrays in PHP using variadic functions from PHP 5.6+ with the spread operator.
With PHP 5.6, variadic functions using the ... operator made array transposition much cleaner.
Modern approach (PHP 5.6+)
function transpose($array) {
return array_map(null, ...$array);
}
Simple, elegant, and easy to understand.
Legacy approach
Before PHP 5.6, the solution was more of a hack than an implementation:
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
It works, but it’s not intuitive. The version with the spread operator is far superior.
Hope it helps!