PHP
Re-index PHP Arrays to Reset Numeric Keys
Learn to re-index PHP arrays, converting associative or sparse numerically-keyed arrays into a fresh, zero-indexed numeric sequence using `array_values()`.
<?php
$sparseArray = [0 => 'apple', 2 => 'banana', 5 => 'orange'];
$associativeArray = ['id1' => 'Alice', 'id2' => 'Bob'];
// After unsetting elements, keys can become sparse
$dynamicArray = ['one', 'two', 'three', 'four'];
unset($dynamicArray[1]); // removes 'two'
unset($dynamicArray[3]); // removes 'four'
print_r($dynamicArray); // Keys are 0, 2
// Re-index the sparse array
$reindexedSparse = array_values($sparseArray);
print_r($reindexedSparse);
// Re-index the associative array (losing original keys)
$reindexedAssociative = array_values($associativeArray);
print_r($reindexedAssociative);
// Re-index the dynamic array after unsetting
$reindexedDynamic = array_values($dynamicArray);
print_r($reindexedDynamic);
?>
How it works: The `array_values()` function is crucial for situations where you need to reset the numeric keys of an array. It returns all the values from an array and assigns new consecutive numeric keys starting from 0. This is especially useful after operations like `unset()` which can leave gaps in numeric keys, or when converting an associative array to a simple list.