how to change the array key to start from 1 instead of 0

后端 未结 10 2142
夕颜
夕颜 2020-12-05 02:09

I have values in some array I want to re index the whole array such that the the first value key should be 1 instead of zero i.e.

By default in PHP the array key st

相关标签:
10条回答
  • 2020-12-05 02:40

    I see this answer is very old, but my solution for this is by adding a +1 to your index. I'll do that because I think this is much faster and easy to read. When you print this it will start from 1 because 0+1 =1, then 2 etc.

      foreach($items as $index => $item){
     echo $index+1 . $item
    }
    
    0 讨论(0)
  • 2020-12-05 02:41

    Simply try this

    $array = array("a","b","c");
    array_unshift($array,"");
    unset($array[0]);
    
    0 讨论(0)
  • 2020-12-05 02:43

    If you are using a range, try this code:

    $data = array_slice(range(0,12), 1, null, true);
    
    // Array ( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 )
    
    0 讨论(0)
  • 2020-12-05 02:49

    try this

    <?php
    $stack = array('a', 'b', 'c', 'd');
    $i= 1;
    foreach($stack as $value){
        $stack2[$i] = $value;
        $i++;
    }
    $stack = stack2;
    ?>
    
    0 讨论(0)
提交回复
热议问题