Perform Matrix Transpose in PHP
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 yourrowsandcolscounts.
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.
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.
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 with outer loop over rows of the transposed matrix (size cols) and inner loop over columns (rows).
📜 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]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.
<?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.
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).
<?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
🔄 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.
rows and cols
They must match the slice of the array you filled. Wrong counts produce garbage or out-of-range logic errors.
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
| Task | Time | Extra space |
|---|---|---|
Transpose m × n | O(m · n) | O(m · n) for the output buffer |
Summary
- Rule:
(AT)ij = Aji; sizes swap fromm×nton×m. - Code: copy into
transposed[i][j] = matrix[j][i]with matching loop bounds. - Double transpose:
(AT)T = A.
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.
8 people found this page helpful
