Skip to content

Instantly share code, notes, and snippets.

@edulan
Created August 10, 2011 12:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edulan/1136654 to your computer and use it in GitHub Desktop.
Save edulan/1136654 to your computer and use it in GitHub Desktop.
PHP matrix transpose using a functional approach
<?php
$matrix = array(
array('a', 1, 2),
array('b', 3, 4),
array('c', 5, 6),
array('d', 7, 8)
);
$transpose = array_reduce(
$matrix,
function ($acum, $row) {
array_walk(
$row,
function($column, $index, $acum) {
$acum[$index][] = $column;
},
&$acum
);
return $acum;
},
array()
);
print_r($transpose);
// Output:
// -------
// a b c d
// 1 3 5 7
// 2 4 6 8
?>
// Taste it!
// php -f transpose.php
@sangharsha
Copy link

any workaround to make this work with newer version of PHP, specially when the pointers are not allowed anymore?

@qRoC
Copy link

qRoC commented Dec 9, 2015

@sangharsha, PHP 5.6:

$matrix = [
    ['a', 1, 2],
    ['b', 3, 4],
    ['c', 5, 6],
    ['d', 7, 8]
];

print_r(array_map(NULL, ...$matrix));

@hoseinz3
Copy link

hoseinz3 commented Dec 6, 2017

@qRoC can you explain how your beautiful trick works?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment