Marco Marco - 6 months ago 62
PHP Question

PHP- pushing value and missing keys into an array

I have an array which looks like this:

array:6 [▼
0 => 2
1 => 2
2 => 2
6 => 5
10 => 3
11 => 1
]


Would I would like to do is, to check somehow if the keys from that array exist in the range of numbers 0 to 11, and if not, to put a value 0 for the missing key and push it to the existing array, or creating a new array with all the values, that would after that look like this:

array:6 [▼
0 => 2
1 => 2
2 => 2
3 => 0
4 => 0
5 => 0
6 => 5
7 => 0
8 => 0
9 => 0
10 => 3
11 => 1
]


I have tried with something like this:

$range = range(0,11);

foreach($myArray as $key => $value){
if(!in_array($key, $range)) {
$myArray[$key] = 0;
}
}


But I just get the same array as at the begging of the question.

Answer

You can create an array with array_fill_keys() and pass it the amount of keys you want with range() and fill the array with 0's. After that you can replace all elements which you already have in your array with array_replace().

<?php

    $array = [2 => 3, 5 => 2, 11 => 7];

    $result = array_replace(array_fill_keys(range(0, 11), 0), $array);
    print_r($result);

?>

The problem with your code is that you only loop over the elements of your array. So if you have just 3 elements you will just loop over these 3 elements.

If you want to fix your current code you would have to loop over the $range and then check if the key, not the value, exists in your array and if yes use the value from it otherwise create the element with the value 0.

Fixed code:

$range = range(0,11);
$result = [];

foreach($range as $key){
    if(isset($array[$key]))
        $result[$key] = $array[$key];
    else
        $result[$key] = 0;
}
Comments