Skip to content
PHP Logo

Is there a recommended approach for identifying and filling gaps in an array without prior knowledge of their positions in PHP?

When needing to identify and fill gaps in an array without prior knowledge of their positions in PHP, one approach is to loop through the array and check for missing keys. If a gap is found, you can fill it by assigning a value to that key. This can be achieved by using a combination of array functions such as array_key_exists() and array_fill().

php
// Sample array with potential gaps
$array = [1 => 'apple', 3 => 'banana', 5 => 'cherry'];

// Identify and fill gaps in the array
$maxKey = max(array_keys($array));
for ($i = 1; $i <= $maxKey; $i++) {
    if (!array_key_exists($i, $array)) {
        $array[$i] = 'missing';
    }
}

// Output the updated array with filled gaps
print_r($array);