Skip to content
Advertisement

PHP rotate matrix counter-clockwise

I am solving a larger problem and at one step I need to rotate a 2D array counter-clockwise.

So if I have this matrix:

1 2 3 4
1 2 3 4
3 4 5 6
3 4 5 6

After the rotation it will be:

4 4 6 6
3 3 5 5
2 2 4 4
1 1 3 3

I have found a solution to rotate it clockwise:

<?php    
$a = array(array(1,2,3,4),array(5,6,7,8),array(9,0,1,2),array(3,4,5,6));
$b = array(); //result

while(count($a)>0)
{
    $b[count($a[0])-1][] = array_shift($a[0]);
    if (count($a[0])==0)
    {
         array_shift($a);
    }
}
?>

The thing is that this has to work even when a is uni-dimensional or has only one element.

So, 1 2 3 4 will become:

4
3
2
1

Advertisement

Answer

$b = call_user_func_array(
    'array_map',
    array(-1 => null) + array_map('array_reverse', $a)
);

I’ll leave it as an exercise for the reader to figure out how it works.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement