PHP

Re-indexing Numeric Array Keys After Deletion

Learn how to reset and re-index the numeric keys of an array after removing elements, ensuring a contiguous sequence, using PHP's `array_values`.

<?php
$items = ['apple', 'banana', 'cherry', 'date'];

unset($items[1]); // Remove 'banana'
// $items is now ['apple', 2 => 'cherry', 3 => 'date']
// Notice the key '1' is missing.

$reindexedItems = array_values($items);
// $reindexedItems is now ['apple', 'cherry', 'date']
// Keys are reset to 0, 1, 2...

$data = [
    'user_id' => 123,
    'name' => 'John Doe',
    'permissions' => ['admin', 'editor']
];

unset($data['user_id']);
// $data is still an associative array
// array_values() would convert it to a numerically indexed array
// For associative arrays, re-indexing keys usually isn't desired.
?>
How it works: When elements are removed from a numerically indexed array using `unset()`, the original keys remain, creating gaps in the numeric sequence. The `array_values()` function is a simple and effective way to 're-index' such an array, returning a new array with all the values from the input array but with keys re-numbered starting from 0. This is particularly useful when you need a contiguous sequence of numeric keys for iteration or further processing.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs