How to increase by 1 all keys in an array?

前端 未结 6 1619
北恋
北恋 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: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)));
    

提交回复
热议问题