how to push an element into the middle of an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

how to push an element into the middle of an array

Post by jasongr »

Hi

I got the folllowing array:
$arr = {4, 9, 10, 3}

I would like to push the value 2 into the array so it would be the new 3rd element
The new final array will be:
$arr = {4, 9, 2, 10, 3}

Is there a simple PHP function that lets you dynamically add elements into a specific index in an array
and automatically shifts the trailing values?

I know that i can implement it myself, but I am looking for a built-in efficient method to do it

regards
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

From PHP Manual
anton at titov dot net
22-Jan-2003 10:23
For the note above: you can use array_splice function to insert a new value (or array) in the middle of array, this will work like your code does:

<?php
$list = array(
"0" => "zero",
"1" => "one",
"2" => "two",
"3" => "three",
"4" => "four",
"5" => "five",
"6" => "six"
);
$value = "New Number Three";
$key = "3";
$new = array_splice($list, $key, 0, $value);
?>
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

Post by jasongr »

Thanks, a lot
This is what I needed
Post Reply