How to transpose a matrix (interchanging of rows and columns) in PHP

1 Answer

0 votes
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

$transpose = array_fill(0, 3, array_fill(0, 3, 0));

$rows = count($matrix);
$cols = count($matrix[0]);

for ($i = 0; $i < $rows; $i++) {
    for ($j = 0; $j < $cols; $j++) {
        $transpose[$j][$i] = $matrix[$i][$j];
    }
}

for ($i = 0; $i < $cols; $i++) {
    for ($j = 0; $j < $rows; $j++) {
        echo $transpose[$i][$j] . " ";
    }
    echo "\n";
}



/*
run:

1 4 7 
2 5 8 
3 6 9 

*/

 



answered Jul 23, 2024 by avibootz
...