Rotate Matrix 90

Rotate a 2D square matrix 90 degrees clockwise by transposing and reversing rows.

Code

General
$n = count($matrix);
$result = [];
for ($i = 0; $i < $n; $i++) {
    $result[$i] = [];
    for ($j = 0; $j < $n; $j++) {
        $result[$i][$j] = $matrix[$n - 1 - $j][$i];
    }
}
return $result;

Parameters

Square matrix

Server

More PHP Snippets