How to increase by 1 all keys in an array?

前端 未结 6 1608
北恋
北恋 2020-12-05 07:04

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

BEFORE:

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


        
相关标签:
6条回答
  • 2020-12-05 07:15
    $count = count($arr);
    for($i=$count; $i>0; $i--){
        $arr[$i] = $arr[$i-1];
    }
    unset($arr[0]);
    
    0 讨论(0)
  • 2020-12-05 07:16

    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));
    
    0 讨论(0)
  • 2020-12-05 07:18

    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;
    
    0 讨论(0)
  • 2020-12-05 07:22

    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;
    },[]);
    
    0 讨论(0)
  • 2020-12-05 07:24

    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.

    0 讨论(0)
  • 2020-12-05 07:35

    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)));
    
    0 讨论(0)
提交回复
热议问题