3v4l.org

run code in 300+ PHP versions simultaneously
<?php $matrix = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], ]; /* i from to i/col i%col i&col i/rows 0 = [0][0] => [0][0] 0 0 0 0 1 = [0][1] => [1][0] 0.3 1 1 0.25 2 = [0][2] => [2][0] 0.6 2 2 0.5 3 = [1][0] => [3][0] 1 0 3 0.75 4 = [1][1] => [0][1] 1.3 1 0 1 5 = [1][2] => [1][1] 1.6 2 1 1.25 6 = [2][0] => [2][1] 2 0 2 1.5 7 = [2][1] => [3][1] 2.3 1 3 1.75 8 = [2][2] => [0][2] 2.6 2 0 2 9 = [3][0] => [1][2] 3 0 1 2.25 10 = [3][1] => [2][2] 3.3 1 2 2.5 11 = [3][2] => [3][2] 3.6 2 3 2.75 */ $rows = count($matrix); $cols = count(current($matrix)); $cells = $rows * $cols; $result = $matrix; for ($i = 0; $i < $cells; ++$i) { $result[$i % $rows][$i / $rows] = $matrix[$i / $cols][$i % $cols]; } var_export($result);

preferences:
25.78 ms | 405 KiB | 5 Q