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

3 Answers

0 votes
function transpose(array $matrix): array {
    $rows = count($matrix);
    $cols = count($matrix[0]);

    $result = array_fill(0, $cols, array_fill(0, $rows, 0));

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

    return $result;
}

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

$transpose = transpose($matrix);

foreach ($transpose as $row) {
    echo implode(" ", $row) . "\n";
}


/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered Jul 23, 2024 by avibootz
edited 1 day ago by avibootz
0 votes
// Use array_map to flip rows and columns.

function transpose(array $matrix): array {
    return array_map(
        fn(...$row) => $row,
        ...$matrix
    );
}

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

$transpose = transpose($matrix);

foreach ($transpose as $row) {
    echo implode(" ", $row) . "\n";
}


/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 1 day ago by avibootz
0 votes
// Use array_column

function transpose(array $matrix): array {
    $cols = count($matrix[0]);
    $result = [];

    for ($i = 0; $i < $cols; $i++) {
        $result[] = array_column($matrix, $i);
    }

    return $result;
}

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

$transpose = transpose($matrix);

foreach ($transpose as $row) {
    echo implode(" ", $row) . "\n";
}


/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 1 day ago by avibootz
...