PHP Insert at particular index

前端 未结 3 339
北荒
北荒 2021-01-26 02:27

I want to move element of array present at 1st index to the 5th index in the array. How can I do that?

3条回答
  •  清酒与你
    2021-01-26 03:12

    If you really mean "move", than that can be something like this

    $from = 1;
    $to = 5;
    $el = $array[$from];
    unset($array[$from]);
    $array = array_merge (
        array_slice($array,0,$to),
        array($el),
        array_slice($array,$to));
    

    Cant test it, but the idea is: We take and remove the Element at $from from the original array, than we split the rest at $to and merge all together. Maybe some index in array_slice() does not match exactly;)

提交回复
热议问题