Last active
December 23, 2017 19:03
-
-
Save u-mulder/a73085b3d1dc19e7666fae9ab09deaa6 to your computer and use it in GitHub Desktop.
Rotating array function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function rotateArray($a, $clockwise = true) | |
{ | |
$r = []; | |
$i = 0; | |
$ti = count($a[0]); | |
$tj = count($a); | |
for (; $i < $ti; $i++) { | |
$row = []; | |
for ($j = 0; $j < $tj; $j++) { | |
if ($clockwise) { | |
array_unshift($row, $a[$j][$i]); | |
} else { | |
$row[] = $a[$j][$i]; | |
} | |
} | |
if ($clockwise) { | |
array_push($r, $row); | |
} else { | |
array_unshift($r, $row); | |
} | |
} | |
return $r; | |
} | |
// tests: | |
$a = [ | |
[1,2,3], | |
[4,5,6], | |
[7,8,9] | |
]; | |
print_r(rotate($a)); | |
echo PHP_EOL; | |
print_r(rotate($a, false)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment