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

后端 未结 10 2216
夕颜
夕颜 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:38

    Ricardo Miguel's solution works best when you're defining your array and want the first key to be 1. But if your array is already defined or gets put together elsewhere (different function or a loop) you can alter it like this:

    $array = array('a', 'b', 'c'); // defined elsewhere
    
    $array = array_filter(array_merge(array(0), $array));
    

    array_merge will put an array containing 1 empty element and the other array together, re-indexes it, array_filter will then remove the empty array elements ($array[0]), making it start at 1.

提交回复
热议问题