PHP

Insert Element into PHP Array at Specific Position

Learn how to insert a new element into an existing PHP array at a precise index without overwriting, using array_splice for dynamic array modification.

<?php
$originalArray = ['apple', 'banana', 'grape'];
$newElement = 'cherry';
$position = 2; // Insert before 'grape' (index 2)

array_splice($originalArray, $position, 0, $newElement);

print_r($originalArray);
// Expected output: Array ( [0] => apple [1] => banana [2] => cherry [3] => grape )

// Example: Insert at the beginning
$newElementBeginning = 'kiwi';
array_splice($originalArray, 0, 0, $newElementBeginning);
print_r($originalArray);
// Expected output: Array ( [0] => kiwi [1] => apple [2] => banana [3] => cherry [4] => grape )
?>
How it works: This snippet demonstrates how to insert a new element into a PHP array at any specified position using `array_splice()`. The function takes the array, the starting offset (position), the length of elements to remove (0 for insertion), and the element(s) to insert. This is highly useful for maintaining specific order or integrating new data into a structured list.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs