Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add missing keys into array

Tags:

arrays

php

I have an array like this, with missing keys:

array(2) {
  [0]=>
  string(4) "Bill"
  [2]=>
  string(13) "[email protected]"
}

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) "[email protected]"
}
like image 645
Richard Knop Avatar asked Mar 16 '11 14:03

Richard Knop


3 Answers

This question is quite old - but I think we can do a little better than the given answers, by providing a three-line solution to fill missing keys in a numerically indexed $array with a $defaultVal - without needing to sort anything first - and still getting a sorted result.

Furthermore, we only do as many loop iterations as there are entries in our original array - and leave the generation of the potentially much larger set of missing indices to the internal php c-code, which can optimize its functions better than we can optimize our userland code.

// array_fill generates a sorted array,
// we merely overwrite its values at certain indices.
// Thus, $newArray will end up sorted,
// even if $array wasn't

$newArray = array_fill(0, max(array_keys($array)), $defaultVal);
foreach ($array as $key => $val) {
    $newArray[$key] = $val;
}

If you need something like this in a context of gigantic arrays or huge numbers of iterations - you might also benefit from using SplFixedArray, which we can use since we know the size of the array - and which is significantly more resource-friendly. You will have to replace the array_fill-part by an explicit loop to set the other values of the SplFixedArray if you don't want them to be null (sadly, no prefillValue can be passed to the constructor).

like image 117
MBauerDC Avatar answered Nov 16 '22 01:11

MBauerDC


Similar to Rinuwise's answer:

$t = array( 0 => "Bill",
            2 => "[email protected]"
          );


$u = $t + array_fill_keys( range(min(array_keys($t)),
                                 max(array_keys($t))
                                ),
                           ''
                           );

ksort($u);

var_dump($u);
like image 36
Mark Baker Avatar answered Nov 16 '22 02:11

Mark Baker


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);
like image 42
RobertPitt Avatar answered Nov 16 '22 03:11

RobertPitt