Let's say you have an array with numeric keys like
$ar = [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g'];
and a defined offset of 4 ($offset = 4
). Now you want to slice a part of that array, starting with the offset.
$slice = array_slice($ar, $offset, null, true);
And you don't just want to keep the original keys, but actually raise them by 1, so the result would be:
Array
(
[5] => e
[6] => f
[7] => g
)
instead of
Array
(
[4] => e
[5] => f
[6] => g
)
Sure, you can loop through the array (foreach, array_walk) and reassign all keys, like:
$new_ar = [];
$raise_by = 1; // Could be any other amount
foreach ($slice as $key => $val) {
$new_ar[$key + $raise_by] = $val;
}
But is there any way to do it without the additional, external loop and (re)assigning the keys? Something like "slice the array at position x and start keys with x + 1"?
EDIT/Possible solutions:
Inspired by the comments, I see 2 possible solutions in addition to Brian's comment in How to increase by 1 all keys in an array?
Static, short and basic:
array_unshift($ar, 0);
$result = array_slice($ar, $offset + 1, null, true);
More flexible, but probably less performant:
$shift = 1;
$slice = array_slice($ar, $offset, null, true);
$ar = array_merge(range(1, $offset + $shift), array_values($slice));
$result = array_slice($ar, $offset + $shift, null, true);
Advantage is that one can shift the keys by any arbitrary value.