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

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.

Example: In this approach, unset($array[$index]) removes the element at the specified index. Note that the array keys are not re-indexed, so you may need additional steps if you require a contiguous array.

PHP
<?php

function removeElement($arr, $index) {
    if (array_key_exists($index, $arr)) {
        unset($arr[$index]);
    }
    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
    [3] => 4
    [4] => 5
)

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.

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
)

Using foreach Loop

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

Example: This approach involves creating a new array and adding elements that are not at the specified index. The resulting array is contiguous and does not have gaps.

PHP
<?php

function removeElement($arr, $index) {
    $newArray = [];
    
    foreach ($arr as $key => $value) {
        if ($key != $index) {
            $newArray[] = $value;
        }
    }
    
    return $newArray;
}

// 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
)