Home » Php » php – How to increase by 1 all keys in an array?

php – How to increase by 1 all keys in an array?

Posted by: admin April 23, 2020 Leave a comment

Questions:

What is the simplest solution to increase by 1 all keys in an array?

BEFORE:

$arr[0] = 'a';
$arr[1] = 'b';
$arr[2] = 'c';

AFTER:

$arr[1] = 'a';
$arr[2] = 'b';
$arr[3] = 'c';
How to&Answers:

You can use

$start_zero = array_values($array); /* Re-Indexing Array To Start From Zero */

And if you want to start it from index 1 use

$start_one = array_combine(range(1, count($array)), array_values($array));

Answer:

Well, there’s one very simple way to do it:

$arr = array('a', 'b', 'c');
array_unshift($arr, null);
unset($arr[0]);
print_r($arr);
/* 
Array
(
    [1] => a
    [2] => b
    [3] => c
)
*/

Will work only for simple dense arrays, of course.

And this is most untrivial (yet both a one-liner AND working for both dense and sparse arrays) way:

$arr = array_flip(array_map(function($el){ return $el + 1; }, array_flip($arr)));

Answer:

I’m not sure why you’d want to do this, but you should just be able to loop through:

$new_array = array();
foreach($arr as $key => $value){
   $new_array[$key+1] = $value;
}
$arr = $new_array;

Answer:

$count = count($arr);
for($i=$count; $i>0; $i--){
    $arr[$i] = $arr[$i-1];
}
unset($arr[0]);

Answer:

I know this question is quite old, but I ran into a similar issue recently and came up with a nice one-liner to solve it for any type of array using an arbitrary integer as the starting key:

$array = array_combine(array_keys(array_fill($starting_index, count($array), 0)), array_values($array));

$starting_index is whatever value you want for the initial integer key, e.g. 3.

This can even be used with arrays holding complex objects, unlike the solution using array_flip and does not limit you to starting the index at 0 or 1 like some of the other solutions.

Answer:

I’m not sure if this qualifies as a one liner but it is a different way of doing it

$result = array_reduce(array_keys($arr),function($carry,$key) use($arr){
     $carry[$key+1] = $arr[$key]; 
     return $carry;
},[]);