I would like to shift the items in array based on given offset. In my current project I need to do this often so I am looking for a common function.
$data = [1, 2, 3, 4, 5, 6];
$data = shift($data, 2);
dd($data); //should result into [3, 4, 5, 6, 1, 2]
function shift($data, $offset) {
// general code
}
Thanks in advance.
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.
Surely as simply as shifting and pushing in a loop
function shift($data, $offset) {
do {
$data[] = array_shift($data);
} while (--$offset > 0);
return $data;
}
EDIT
If you need to work with negative offsets as well,
function shift($data, $offset) {
if ($offset > 0) {
do {
$data[] = array_shift($data);
} while (--$offset > 0);
} elseif ($offset < 0) {
do {
array_unshift($data, array_pop($data));
} while (++$offset < 0);
}
return $data;
}