views:

143

answers:

2

I need help converting this code from this thread: http://stackoverflow.com/questions/646468/how-to-rotate-a-2d-array-of-integers

to PHP arrays.

int [,] newArray = new int[4,4];


for (int i=3;i>=0;--i) {
    for (int j=0;j<4;++j) {
        newArray[j,3-i] = array[i,j];
    }
}

Also, will this code work if the blocks are off-center?

A: 

Without putting any thought into this at all, "jagged arrays" are pretty much identical to "rectangular arrays" (which PHP doesn't support), so use em:

$newArray = array(array())

for($i=3; $i >= 0; --$i) {
    for($j=0; $j < 4; ++$j) {
        $newArray[$j][3-$i] = $oldArray[$i][$j];
    }
}
Mark
+1  A: 

Jacob King, on his blog, has written a PHP function that can rotate a given array 90, 180, and 270 degrees. See his entry "Rotating 2-dimensional Arrays" online at: http://www.jacobkking.com/story/rotating-2-dimensional-arrays

Jonathan Sampson