How to insert an item at the beginning of an array in PHP?

后端 未结 9 816
萌比男神i
萌比男神i 2020-12-02 14:53

I know how to insert it to the end by:

$arr[] = $item;

But how to insert it to the beginning?

9条回答
  •  情话喂你
    2020-12-02 15:44

    Or you can use temporary array and then delete the real one if you want to change it while in cycle:

    $array = array(0 => 'a', 1 => 'b', 2 => 'c');
    $temp_array = $array[1];
    
    unset($array[1]);
    array_unshift($array , $temp_array);
    

    the output will be:

    array(0 => 'b', 1 => 'a', 2 => 'c')
    

    and when are doing it while in cycle, you should clean $temp_array after appending item to array.

提交回复
热议问题