-3

I have the following array:

[answer] => Array
    (
        [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:

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

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

[answer] => Array
    (
        [0] => A
        [1] => X
        [2] => E
    )
DCR
  • 14,737
  • 12
  • 52
  • 115

2 Answers2

1

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);
imvain2
  • 15,480
  • 1
  • 16
  • 21
0

I think the simplest way is to sort array using ksort: https://www.php.net/manual/en/function.ksort.php.

$input = [
  0 => 'A',
  2 => 'E'
];
ksort($input);
var_export($input);

Or if you don't want to sort for some reason, you can use another array to store data in order you expect:

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

for($i = 0; $i < 3; $i++){
      $temp[] = isset($input[$i]) ? $arr[$i] : 'X';
}

var_export($temp);

Output for two methods (as expected):

array (
  0 => 'A',
  1 => 'X',
  2 => 'E',
)
Calliso
  • 31
  • 6