Search code examples
phparrays

Insert missing elements of an indexed array with a default value and ensure an indexed result


I have the following array:

$answer = [0 => 'A', 2 => 'E'];

I run the following code:

for ($i = 0; $i < 3; $i++) {
   if (!isset($answer[$i])) $answer[$i] = "X"; 
}

and get the following array with unordered keys:

Array
    (
        [0] => A
        [2] => E
        [1] => X
    )

Is there a way to preserve the order so we get:

Array
    (
        [0] => A
        [1] => X
        [2] => E
    )

Solution

  • You can use ksort and it will sort the array in place.

    https://www.php.net/manual/en/function.ksort.php

    $answer =["0" => "A","2" => "E"];    
    
    for ($i = 0; $i < 3; $i++){
       if (!isset($answer[$i]))$answer[$i] = "X"; 
    }
    
    ksort($answer);