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

后端 未结 9 796
萌比男神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:21

    Insert an item in the beginning of an associative array with string/custom key

    'valueOne', 'keyTwo'=>'valueTwo'];
    
    $array = array_reverse($array);
    
    $array['newKey'] = 'newValue';
    
    $array = array_reverse($array);
    

    RESULT

    [
      'newKey' => 'newValue',
      'keyOne' => 'valueOne',
      'keyTwo' => 'valueTwo'
    ]
    

提交回复
热议问题