Add elements to array which has gapped numeric keys to form an indexed array / list

This should be faster for larger arrays. For smaller arrays any method will do.

$existingKeys = array_keys($array);

//you can use any value instead of null
$newKeys = array_fill_keys(range(min($existingKeys), max($existingKeys)), null);
$array += $newKeys;

//optional, probably not needed
ksort($array);

Leave a Comment