How to use array_splice() Function In PHP

The array_splice() function removes a portion of an array and can be used to remove an element at a specific index, while also re-indexing the array.

Example: Here, array_splice($array, $index, 1) removes one element at the specified index and re-indexes the array, making it contiguous again.

PHP
<?php

function removeElement($arr, $index) {
    if (array_key_exists($index, $arr)) {
        array_splice($arr, $index, 1);
    }
    
    return $arr;
}

// Driver code
$arr = [1, 2, 3, 4, 5];
$index = 2;
$updatedArr = removeElement($arr, $index);
print_r($updatedArr);

?>

Output
Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
)

Remove an Element at Given Index from Array in PHP

Given an array and an index, the task is to remove the element at a given index from an array in PHP.

Below are the approaches to remove an element at a given index from an array using PHP:

Table of Content

  • Using unset() Function
  • Using array_splice() Function
  • Using foreach Loop

Similar Reads

Using unset() Function

The unset() function is used to remove an element at a specific index. This function effectively removes the element but leaves the array keys unchanged....

Using array_splice() Function

The array_splice() function removes a portion of an array and can be used to remove an element at a specific index, while also re-indexing the array....

Using foreach Loop

A manual method involves using a foreach loop to iterate over the array and rebuild it without the specified element....