Add missing keys into array Add missing keys into array arrays arrays

Add missing keys into array


Similar to Rinuwise's answer:

$t = array( 0 => "Bill",            2 => "billy@kid.com"          );$u = $t + array_fill_keys( range(min(array_keys($t)),                                 max(array_keys($t))                                ),                           ''                           );ksort($u);var_dump($u);


your questions is very vague and hard to understand exactly what you want, from my interpretation it seems you want to insert a key into the array moving the current keys along the index line.

you may want to try something like this:

function cleanArray(&$array){    end($array);    $max = key($array); //Get the final key as max!    for($i = 0; $i < $max; $i++)    {        if(!isset($array[$i]))        {            $array[$i] = '';        }    }}cleanArray($array);


If you want to automate setting the empty keys, you can do

$keys = array_keys($array);$maxkey = end($keys); // it will fill only the values between 0 and last keyfor ($i = 0; $i < $maxkey; $i++) {    if (!array_key_exists($i, $array)) {        $array[$i] = '';    }}