array_splice(): Modifying Arrays in PHP

The array_splice() function in PHP is used to remove, replace, or insert elements in an array. It modifies the original array, making it a versatile tool for array manipulation.

Syntax

array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = [])
  • $array: The array to modify.
  • $offset: The position at which to start the changes.
  • $length (optional): The number of elements to remove. Defaults to removing all elements from the offset.
  • $replacement (optional): Elements to insert at the offset position.

Example 1: Removing Elements from an Array

$fruits = ['apple', 'banana', 'cherry', 'date'];
array_splice($fruits, 1, 2);
print_r($fruits);
Output:
Array
(
    [0] => apple
    [1] => date
)

Example 2: Replacing Elements in an Array

$fruits = ['apple', 'banana', 'cherry', 'date'];
array_splice($fruits, 1, 2, ['mango', 'peach']);
print_r($fruits);
Output:
Array
(
    [0] => apple
    [1] => mango
    [2] => peach
    [3] => date
)

Example 3: Inserting Elements without Removing Any

$fruits = ['apple', 'banana', 'cherry', 'date'];
array_splice($fruits, 2, 0, ['grape', 'kiwi']);
print_r($fruits);
Output:
Array
(
    [0] => apple
    [1] => banana
    [2] => grape
    [3] => kiwi
    [4] => cherry
    [5] => date
)

Example 4: Removing All Elements After a Specific Position

$fruits = ['apple', 'banana', 'cherry', 'date'];
array_splice($fruits, 2);
print_r($fruits);
Output:
Array
(
    [0] => apple
    [1] => banana
)

Conclusion

The array_splice() function is a powerful tool for modifying arrays in PHP. Whether you need to remove, replace, or insert elements at specific positions, this function offers flexibility while modifying the original array directly.


Replace array values Difference between arrays considering values
Array REFERENCE
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer