How to insert element in array in the middle

I don't know, ow to insert element in array in the middle with php. I know how it's solve in c++ or c#, but in php i don't know. Please help me.

I used

$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

but this add in begin of array not middle.

Upvotes: 0

Views: 204

Answers (2)

Uxío
Uxío

Reputation: 1371

$stack = array("orange", "banana");
$inserted = array("apple", "raspberry");
$position = 1;
array_splice( $stack, $position, 0, $inserted );

Upvotes: 0

Barmar
Barmar

Reputation: 780889

Use array_splice():

array_splice($stack, 1, 0, array("apple", "raspberry"));

Specifying a length of 0 means it should just insert the new elements at that position, without removing anything.

If you're just inserting a single element into the array, you don't need to wrap it in an array:

array_splice($stack, 1, 0, "apple");

Upvotes: 2

Related Questions