Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert new item in array on any position in PHP

Tags:

arrays

php

insert

How can I insert a new item into an array on any position, for example in the middle of array?

like image 431
kusanagi Avatar asked Sep 26 '10 09:09

kusanagi


People also ask

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

The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array. Tip: You can add one value, or as many as you like.

Can you add to an array in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).


1 Answers

You may find this a little more intuitive. It only requires one function call to array_splice:

$original = array( 'a', 'b', 'c', 'd', 'e' ); $inserted = array( 'x' ); // not necessarily an array, see manual quote   array_splice( $original, 3, 0, $inserted ); // splice in at position 3 // $original is now a b c x d e 

If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL.

RETURN VALUE: To be noted that the function does not return the desired substitution. The $original is passed by reference and edited in place. See the expression array &$array with & in the parameters list .

like image 78
jay.lee Avatar answered Oct 11 '22 04:10

jay.lee