Perform Matrix Transpose in PHP

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code Examples
2D arrays

What you’ll learn

  • What the transpose AT means: turn rows into columns so (AT)ij = Aji.
  • How to implement it with a second buffer transposed[cols][rows] and nested loops.
  • A 2×3 reference example (output shape 3×2), a 3×3 square example, plus a live preview.

Overview

Transposing is one of the gentlest matrix operations: you copy each value from position (j, i) in the original into position (i, j) in the result. The grid “flips” so height and width swap.

Two programs

Rectangle 2×3 and square 3×3.

Live preview

Same numbers as the first program, computed in the browser.

Why a copy?

A separate array avoids stepping on values you still need while building the transpose.

Prerequisites

2D arrays, nested for loops, and basic output formatting.

  • Basic PHP arrays, loops, functions, and echo.
  • Indexing with matrix[row][col] and knowing your rows and cols counts.

What is the transpose?

The transpose of a matrix A is written AT. Its entries satisfy (AT)ij = Aji: row and column indices are swapped.

So if A has m rows and n columns, AT has n rows and m columns.

Shape m×n → n×m
Flip twice (AT)T = A

Formal rule

For all valid indices, (AT)ij = Aji. Implementation-wise you often write transposed[i][j] = matrix[j][i] when i ranges over columns of the original and j over rows, matching the loop bounds below.

Live preview

Built-in 2×3 sample from example 1. Press the button to see A and AT.

Matches the first PHP program’s numbers.

Live result
Press “Transpose sample”.

Algorithm

Goal: given matrix[rows][cols], fill transposed[cols][rows] with transposed[i][j] = matrix[j][i].

Allocate output shape

The result has cols rows and rows columns when the input has rows × cols.

Copy with swapped indices

Nested loops: for each i in 0 .. cols-1 and j in 0 .. rows-1, assign transposed[i][j] = matrix[j][i].

Print

Print with outer loop over rows of the transposed matrix (size cols) and inner loop over columns (rows).

📜 Pseudocode

Pseudocode
function transpose(matrix, rows, cols, out):   // out is cols x rows
    for i from 0 to cols - 1:
        for j from 0 to rows - 1:
            out[i][j] ← matrix[j][i]
1

Transpose a 2×3 matrix (reference)

Classic layout: store the original in a fixed upper bound array, pass real rows and cols, build transposed[cols][rows]. Also prints the original for context.

c
<?php
function transposeMatrix(array $matrix, int $rows, int $cols): array
{
    $transposed = [];
    for ($i = 0; $i < $cols; $i++) {
        for ($j = 0; $j < $rows; $j++) {
            $transposed[$i][$j] = $matrix[$j][$i];
        }
    }
    return $transposed;
}

function printMatrix(array $matrix): void
{
    foreach ($matrix as $row) {
        echo implode("\t", $row) . "\n";
    }
}

$matrix = [[1, 2, 3], [4, 5, 6]];
$rows = 2;
$cols = 3;
$transposed = transposeMatrix($matrix, $rows, $cols);

echo "Original ($rows x $cols):\n";
printMatrix($matrix);
echo "Transposed Matrix ($cols x $rows):\n";
printMatrix($transposed);
?>

Explanation

The assignment transposed[i][j] = matrix[j][i] is the whole idea. Loop ranges follow the swapped dimensions: i runs cols times, j runs rows times.

2

Transpose a 3×3 matrix

Square example: first row 1 2 3 becomes first column of the result. Still uses a separate buffer (simplest and safest for learners).

c
<?php
function transposeSquare(array $a): array
{
    $n = count($a);
    $out = array_fill(0, $n, array_fill(0, $n, 0));
    for ($i = 0; $i < $n; $i++) {
        for ($j = 0; $j < $n; $j++) {
            $out[$i][$j] = $a[$j][$i];
        }
    }
    return $out;
}

function printMatrixWithTitle(string $title, array $m): void
{
    echo $title . "\n";
    foreach ($m as $row) {
        echo implode(" ", $row) . "\n";
    }
}

$a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
$t = transposeSquare($a);

printMatrixWithTitle("A", $a);
echo "\n";
printMatrixWithTitle("A^T", $t);
?>

Explanation

For square matrices, out is the same shape as a. In-place transpose (without extra memory) is possible for squares but easier to get wrong; two buffers keep the lesson clear.

Extensions

In place (square only). Swap a[i][j] with a[j][i] for i < j to avoid using a second matrix; watch indexing carefully.

Dynamic sizes. For variable rows and cols, allocate rows*cols storage (or VLAs if your environment allows) instead of a fixed MAX.

❓ FAQ

Take every row of the original matrix and write it as a column of a new matrix (or swap row index with column index at each entry).
It has 3 rows and 2 columns. In general an m x n matrix becomes n x m.
The entry at row i, column j of A^T equals the entry at row j, column i of A. In symbols: (A^T)_ij = A_ji.
In general a non-square matrix changes shape, so you usually need a second buffer. For a square n x n matrix you can swap across the diagonal in place with care.
So each assignment transposed[i][j] = matrix[j][i] does not overwrite data you still need from the original matrix.
You touch every element once to fill the transpose: O(m*n) time for an m x n matrix, with O(m*n) space for the output array.

🔄 Input / output

To experiment, change the numbers inside matrix and adjust rows and cols so they stay consistent with how much of the array you actually use.

Edge cases

Keep dimensions honest and buffers large enough.

Bounds

rows and cols

They must match the slice of the array you filled. Wrong counts produce garbage or out-of-range logic errors.

MAX

Fixed array size

MAX must be at least max(rows, cols) for both dimensions of both matrices when using one big square buffer.

⏱️ Time and space complexity

TaskTimeExtra space
Transpose m × nO(m · n)O(m · n) for the output buffer

Summary

  • Rule: (AT)ij = Aji; sizes swap from m×n to n×m.
  • Code: copy into transposed[i][j] = matrix[j][i] with matching loop bounds.
  • Double transpose: (AT)T = A.
Did you know?

The transpose flips a matrix across its diagonal: rows become columns. If A is m × n, then AT is n × m, and (AT)T = A.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful