Cut out part of the array and raise the numeric key by x value

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; // Could be any other amount
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);

, .

+4
4

. . array_combine 5-7

$ar = [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g'];
$offset = 4;
$slice = array_slice($ar, $offset, null, true);
$slice = array_combine(range($offset+1, count($slice)+$offset), array_values($slice));//<--------check this

echo "<pre>";
print_r($slice);
+1

,

$ar = [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g'];

$slice = array_slice($ar, '4', null, true);


    $new_arr = array();
    foreach($slice as $key => $val)
    {
        $key = $key + 1;
        $new_arr[$key] = $val;
        $key++;
    }

, , @. , .

0

0, , .

$ar=array_splice($ar,0,0,' ');
$slice = array_slice($ar, $offset, null, true);
0
<?php
$ar = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g');
$ar = array_combine(
        array_map(function ($key) { return ++$key; }, array_keys($ar)),
        $ar
);
$offset = 4;
$sliced = array_slice($ar, $offset, count($ar), TRUE);
echo '<pre>';print_r($sliced);echo '</pre>';
0

Source: https://habr.com/ru/post/1681682/


All Articles