Skip to content
Advertisement

Add missing keys into array

I have an array like this, with missing keys:

array(2) {
  [0]=>
  string(4) "Bill"
  [2]=>
  string(13) "billy@kid.com"
}

How can I add missing keys to it with empty strings as values? I want this as a result:

array(3) {
  [0]=>
  string(4) "Bill"
  [1]=>
  string(0) ""
  [2]=>
  string(13) "billy@kid.com"
}

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement