You can use laravel collection macro to create your own custom functions.
Below is the macro which will support the negative offset as well.
$collection = collect([1, 2, 3, 4, 5, 6]);
$rotate = $collection->rotate(2);
$rotate->toArray();
// [3, 4, 5, 6, 1, 2]
Collection::macro('rotate', function ($offset) {
if ($this->isEmpty()) {
return new static;
}
$count = $this->count();
$offset %= $count;
if ($offset < 0) {
$offset += $count;
}
return new static($this->slice($offset)->merge($this->take($offset)));
});
You can use collection in native PHP as well but below function can be used in native PHP.
function array_rotate($array, $shift) {
$shift %= count($array);
if($shift < 0) $shift += count($array);
return array_merge(array_slice($array, $shift, NULL, true), array_slice($array, 0, $shift, true));
}
Both functions will preserve keys if explicitly specified.