How To Insert New Item Any Position In PHP Array

Arrays are fundamental data structures in PHP, and you often need to manipulate them by adding, modifying, or removing elements. In this tutorial you will learn how to insert a new item at any position in a PHP array with different methods.

Using array_splice() to Insert Element in Any Position

The array_splice() function allows you to insert elements into an array at a specified position while preserving the existing elements.

$fruits = ["apple", "banana", "cherry"];
$newFruit = "orange";

// Insert $newFruit at index 1
array_splice($fruits, 1, 0, $newFruit);

print_r($fruits);
Array
(
    [0] => apple
    [1] => orange
    [2] => banana
    [3] => cherry
)

In this example, array_splice($fruits, 1, 0, $newFruit) inserts “orange” at index 1 of the $fruits array without removing any elements. You specify the array, the starting index, the number of elements to remove (0 in this case), and the new item to insert.

Using array_slice() and Array Concatenation

Another approach is to use array_slice() to split the array into two parts, insert the new item in between, and then concatenate the two parts back together.

$fruits = ["apple", "banana", "cherry"];
$newFruit = "orange";
$position = 1;

// Split the array into two parts
$part1 = array_slice($fruits, 0, $position);
$part2 = array_slice($fruits, $position);

// Insert $newFruit in between
$fruits = array_merge($part1, [$newFruit], $part2);

print_r($fruits);
Array
(
    [0] => apple
    [1] => orange
    [2] => banana
    [3] => cherry
)

In this example, we use array_slice() to split the array into two parts, insert “orange” in between, and then use array_merge() to concatenate the parts back together.

Using a Loop to Insert Item at Any Position of Array

You can also insert a new item into an array by iterating through it and manually rearranging the elements.

$fruits = ["apple", "banana", "cherry"];
$newFruit = "orange";
$position = 1;

$result = [];

foreach ($fruits as $key => $fruit) {
    if ($key == $position) {
        $result[] = $newFruit;
    }
    $result[] = $fruit;
}

$fruits = $result;

print_r($fruits);
Array
(
    [0] => apple
    [1] => orange
    [2] => cherry
)

Using array_splice() to Replace an Element

If you want to replace an element at a specific position with a new item, you can use array_splice() with a non-zero length to remove the existing element and insert the new one.

$fruits = ["apple", "banana", "cherry"];
$newFruit = "orange";
$position = 1;

// Replace the element at index 1 with $newFruit
array_splice($fruits, $position, 1, $newFruit);

print_r($fruits);
Array
(
    [0] => apple
    [1] => orange
    [2] => cherry
)

In this example, replaces the element at index 1 (which is “banana”) with “orange.”

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy