Removing Array Element and Re-Indexing in PHP

In PHP, when you remove an element from an array using unset(), the original array keys are preserved, which can create gaps in the index sequence. To re-index the array with consecutive numeric keys starting from 0, you can use the array_values() function.

Example

The following example demonstrates removing an array element and re-indexing −

<?php
    $arr = array("John", "Jacob", "Tom", "Tim");
    echo "Original Array...<br>";
    foreach($arr as $key => $value) {
        echo "Index $key = $value<br>";
    }
    
    // Remove element at index 1
    unset($arr[1]);
    echo "\nAfter removing index 1 (without re-indexing)...<br>";
    foreach($arr as $key => $value) {
        echo "Index $key = $value<br>";
    }
    
    // Re-index the array
    $result = array_values($arr);
    echo "\nAfter re-indexing with array_values()...<br>";
    foreach($result as $key => $value) {
        echo "Index $key = $value<br>";
    }
?>
Original Array...
Index 0 = John
Index 1 = Jacob
Index 2 = Tom
Index 3 = Tim

After removing index 1 (without re-indexing)...
Index 0 = John
Index 2 = Tom
Index 3 = Tim

After re-indexing with array_values()...
Index 0 = John
Index 1 = Tom
Index 2 = Tim

Alternative Methods

You can also use array_splice() which removes elements and automatically re-indexes −

<?php
    $arr = array("John", "Jacob", "Tom", "Tim");
    echo "Original Array...<br>";
    print_r($arr);
    
    // Remove 1 element starting from index 1
    array_splice($arr, 1, 1);
    echo "\nAfter array_splice() - automatically re-indexed...<br>";
    print_r($arr);
?>
Original Array...
Array
(
    [0] => John
    [1] => Jacob
    [2] => Tom
    [3] => Tim
)

After array_splice() - automatically re-indexed...
Array
(
    [0] => John
    [1] => Tom
    [2] => Tim
)

Conclusion

Use unset() followed by array_values() when you want to preserve other elements' positions, or use array_splice() for automatic re-indexing during removal.

Updated on: 2026-03-15T08:23:39+05:30

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements