Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,240 questions

56,143 answers

573 users

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 May 25 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 May 25 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 May 25 by avibootz
...