3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php // This code is public domain. The original author is Marc Ermshaus. error_reporting(-1); /** * Circularly shifts an array * * Shifts to right for $steps > 0. Shifts to left for $steps < 0. Keys are * preserved. * * @param array $array Array to shift * @param int $steps Steps to shift array by * @return array Resulting array */ function array_shift_circular(array $array, $steps = 1) { if (!is_int($steps)) { throw new InvalidArgumentException( 'steps has to be an (int)'); } if ($steps === 0) { return $array; } $l = count($array); if ($l === 0) { return $array; } $steps = $steps % $l; $steps *= -1; return array_merge(array_slice($array, $steps), array_slice($array, 0, $steps)); } header('content-type: text/plain'); $a = range(0, 9); $l = count($a); for ($i = $l * -2; $i <= $l * 2; $i++) { printf("% 3s : %s\n", $i, implode(', ', array_shift_circular($a, $i))); } ?>
Output for 5.6.30, hhvm-3.18.5 - 3.22.0, 7.0.30 - 7.3.0beta1
-20 : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 -19 : 9, 0, 1, 2, 3, 4, 5, 6, 7, 8 -18 : 8, 9, 0, 1, 2, 3, 4, 5, 6, 7 -17 : 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 -16 : 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 -15 : 5, 6, 7, 8, 9, 0, 1, 2, 3, 4 -14 : 4, 5, 6, 7, 8, 9, 0, 1, 2, 3 -13 : 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 -12 : 2, 3, 4, 5, 6, 7, 8, 9, 0, 1 -11 : 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 -10 : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 -9 : 9, 0, 1, 2, 3, 4, 5, 6, 7, 8 -8 : 8, 9, 0, 1, 2, 3, 4, 5, 6, 7 -7 : 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 -6 : 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 -5 : 5, 6, 7, 8, 9, 0, 1, 2, 3, 4 -4 : 4, 5, 6, 7, 8, 9, 0, 1, 2, 3 -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