PHP

Insert or Replace Array Elements at Specific Position

Master `array_splice` to insert new elements into an array at a precise index, or replace existing elements, controlling the array's structure.

<?php

$fruits = ['apple', 'banana', 'orange', 'grape'];

// 1. Insert an element without removing any existing elements
// array_splice(array, offset, length, replacement)
// offset: Start from index 2 (third element)
// length: 0 (don't remove any elements)
// replacement: ['mango'] (insert 'mango')
array_splice($fruits, 2, 0, ['mango']);
print_r($fruits);
// Expected: Array ( [0] => apple [1] => banana [2] => mango [3] => orange [4] => grape )

// Reset for next example
$fruits = ['apple', 'banana', 'orange', 'grape'];

// 2. Replace one element with another
// offset: Start from index 1 ('banana')
// length: 1 (remove 1 element)
// replacement: ['kiwi'] (replace with 'kiwi')
array_splice($fruits, 1, 1, ['kiwi']);
print_r($fruits);
// Expected: Array ( [0] => apple [1] => kiwi [2] => orange [3] => grape )

?>
How it works: The `array_splice()` function is highly versatile for modifying arrays by inserting, removing, or replacing elements. It takes the array by reference, an offset to start from, an optional length of elements to remove, and an optional replacement array. Setting `length` to 0 inserts elements without removal, while a positive `length` replaces existing elements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs