skip to Main Content

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
    )

2

Answers


  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);
    
    Login or Signup to reply.
  2. 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',
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search