Skip to content

Instantly share code, notes, and snippets.

@u-mulder
Last active December 23, 2017 19:03
Show Gist options
  • Save u-mulder/a73085b3d1dc19e7666fae9ab09deaa6 to your computer and use it in GitHub Desktop.
Save u-mulder/a73085b3d1dc19e7666fae9ab09deaa6 to your computer and use it in GitHub Desktop.
Rotating array function
<?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