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 specific offset 4 ( $offset = 4). Now you want to slice part of this array, starting at offset.
$slice = array_slice($ar, $offset, null, true);
And you do not just want to keep the original keys, but actually raise them by 1, so the result will be:
Array
(
[5] => e
[6] => f
[7] => g
)
instead
Array
(
[4] => e
[5] => f
[6] => g
)
Of course, you can iterate over an array (foreach, array_walk) and reassign all keys, for example:
$new_ar = [];
$raise_by = 1;
foreach ($slice as $key => $val) {
$new_ar[$key + $raise_by] = $val;
}
But is there a way to do this without an additional external loop and (re) key assignment? Something like "slice an array at position x and start the keys with x + 1"?
EDIT / Possible Solutions:
Inspired by the comments, I see 2 possible solutions in addition to Brian's comment. How do I increase all keys in the array by 1?
, :
array_unshift($ar, 0);
$result = array_slice($ar, $offset + 1, null, true);
, , , :
$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);
, .