function rotate90Clockwise($matrix) {
$rows = count($matrix); // Number of rows
$cols = count($matrix[0]); // Number of columns
$rotated = array_fill(0, $cols, array_fill(0, $rows, 0));
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
$rotated[$j][$rows - 1 - $i] = $matrix[$i][$j]; // Mapping to rotated position
}
}
return $rotated;
}
function printMatrix($matrix) {
foreach ($matrix as $row) {
echo implode(" ", $row) . PHP_EOL;
}
}
$matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
echo "Original Matrix:\n";
printMatrix($matrix);
$rotated = rotate90Clockwise($matrix);
echo "\nRotated Matrix:\n";
printMatrix($rotated);
/*
run:
Original Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
Rotated Matrix:
9 5 1
10 6 2
11 7 3
12 8 4
*/