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
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





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