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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to rotate a matrix 90 degrees clockwise in PHP

2 Answers

0 votes
function rotate90Clockwise(&$matrix) {
    $rows = count($matrix); // Number of rows
    
    // Step 1: Transpose the matrix
    for ($i = 0; $i < $rows; $i++) {
        for ($j = $i; $j < $rows; $j++) {
            $temp = $matrix[$i][$j];
            $matrix[$i][$j] = $matrix[$j][$i];
            $matrix[$j][$i] = $temp;
        }
    }
 
    // Step 2: Reverse each row
    for ($i = 0; $i < $rows; $i++) {
        $matrix[$i] = array_reverse($matrix[$i]);
    }
}
 
function printMatrix($matrix) {
    foreach ($matrix as $row) {
        echo implode(" ", $row) . PHP_EOL;
    }
}
 
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
 
echo "Original Matrix:\n";
printMatrix($matrix);
 
rotate90Clockwise($matrix);
 
echo "\nRotated Matrix:\n";
printMatrix($matrix);
 
 
  
/*
run:
  
Original Matrix:
1 2 3
4 5 6
7 8 9

Rotated Matrix:
7 4 1
8 5 2
9 6 3
 
*/

 



answered May 29, 2025 by avibootz
edited May 29, 2025 by avibootz
0 votes
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

*/

 



answered May 29, 2025 by avibootz

Related questions

2 answers 256 views
2 answers 290 views
2 answers 312 views
2 answers 255 views
2 answers 253 views
...