While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.
The following array_rotate() function uses array_merge and array_shift to reliably rotate an array forwards or backwards, preserving keys. If you know you can trust your $array to be an array and $shift to be between 0 and the length of your array, you can skip the function definition and use just the return expression in your code.
<?php
function array_rotate($array, $shift) {
if(!is_array($array) || !is_numeric($shift)) {
if(!is_array($array)) error_log(__FUNCTION__.' expects first argument to be array; '.gettype($array).' received.');
if(!is_numeric($shift)) error_log(__FUNCTION__.' expects second argument to be numeric; '.gettype($shift)." `$shift` received.");
return $array;
}
$shift %= count($array); if($shift < 0) $shift += count($array);return array_merge(array_slice($array, $shift, NULL, true), array_slice($array, 0, $shift, true));
}
?>
A few simple tests:
<?php
$array=array("foo"=>1,"bar"=>2,"baz"=>3,4,5);
print_r(array_rotate($array, 2));
print_r(array_rotate($array, -2));
print_r(array_rotate($array, count($array)));
print_r(array_rotate($array, "4"));
print_r(array_rotate($array, -9));
?>