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]"
}
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).
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);
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With