tags:

views:

38

answers:

3

how can i add new item to array? for example in the middle of array?

+1  A: 

In PHP doesn't exist somethings like insertAtIndex. You need to create a function like array_insert (follow the link for the implementation).

Luca Bernardi
+3  A: 
$a = array(1,2,3,4);
$b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2));
// $b = array(1,2,5,3,4)
Amber
+2  A: 

you may find this a little more intuitive, it also only requires one function call:

$original = array( 'a','b','c','d','e' );
$inserted = array( 'x' );

array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e
jay.lee
This is the correct answer, although it should be pointed out that $inserted need not be an array. (See the note in the manual.)
GZipp