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

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

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

    RESULT

    [
      'newKey' => 'newValue',
      'keyOne' => 'valueOne',
      'keyTwo' => 'valueTwo'
    ]
    
    0 讨论(0)
  • 2020-12-02 15:24

    This will help

    http://www.w3schools.com/php/func_array_unshift.asp

    array_unshift();
    
    0 讨论(0)
  • 2020-12-02 15:26

    Use array_unshift($array, $item);

    $arr = array('item2', 'item3', 'item4');
    array_unshift($arr , 'item1');
    print_r($arr);
    

    will give you

    Array
    (
     [0] => item1
     [1] => item2
     [2] => item3
     [3] => item4
    )
    
    0 讨论(0)
  • 2020-12-02 15:36

    For an associative array you can just use merge.

    $arr = array('item2', 'item3', 'item4');
    $arr = array_merge(array('item1'), $arr)
    
    0 讨论(0)
  • 2020-12-02 15:37

    Use function array_unshift

    0 讨论(0)
  • 2020-12-02 15:37

    With custom index:

    $arr=array("a"=>"one", "b"=>"two");
        $arr=array("c"=>"three", "d"=>"four").$arr;
    
        print_r($arr);
        -------------------
        output:
        ----------------
        Array
        (
        [c]=["three"]
        [d]=["four"]
        [a]=["two"]
        [b]=["one"]
        )
    
    0 讨论(0)
提交回复
热议问题