skip to Main Content

I am creating an array by doing $x = [];

If I do:

  $x = [];
  $x[2] = 'a';
  $x[1] = 'b';
  $x[0] = 'c';
  echo json_encode($x);

I get: {"2":"a","1":"b","0":"c"}.

If I do:

  $x = [];
  array_push($x,'c');
  array_push($x,'b');
  array_push($x,'a');
  echo json_encode($x);

I get: ["c","b","a"]

Can I build an array like in the array_push example by position $x[] instead of an associative array?

I want to do the $x[] syntax to update the array by position and get the ["c","b","a"] array. There must be some syntax or construction that I am not using correctly.

Thanks in advance for any help.

4

Answers


  1. Chosen as BEST ANSWER

    Based on the comments, this cannot be controlled like in javascript where you can create an array by doing [] and an object by doing {}.

    My solution is this:

      $x = [];
      $x[2] = 'a';
      $x[1] = 'b';
      $x[0] = 'c';
      echo json_encode($x);
      $y = [];
      $l = count($x);
      for ($i=0;$i<$l;$i++){
       array_push($y,$x[$i]);
      }
      echo json_encode($y);
    

  2. Adding in ksort(), before the JSON encoding, does the trick:

    $x = [];
    $x[2] = 'a';
    $x[1] = 'b';
    $x[0] = 'c';
    ksort($x);
    echo json_encode($x);
    

    This sorts the array by the keys specified and returns:

    ["c","b","a"]
    

    See: https://3v4l.org/Bi28c

    Login or Signup to reply.
  3. You can use array_unshift($x, ...['a', 'b', 'c']) (or by one element) instead of array_push to always add element to the beginning of array instead of end.

    Example

    Login or Signup to reply.
  4. Although users (and other languages – including JSON, which is not JavaScript) often distinguish between "associative arrays" and "ordered arrays", PHP does not.

    Every array allows access to its items in two ways:

    • Every array has a list of items, in a defined order
    • Every item has a key and a value
    • If you access an item using $foo[$bar], you are looking up or setting an item by its key
    • If you add an item to an array, it will be the last item in the list
    • If you do not specify the key for your new item, PHP will allocate one for you (the current highest number, plus 1)

    The reason your current code doesn’t give the result you wanted is that from PHP’s point of view, there is no such thing as "the third position" in an empty array. The first item added to an empty array is always the first in the list, regardless of its key.

    You can sort the items based on their keys with ksort; but this won’t create or delete any items, it will just change the order in the list.

    $x = [];
    $x[2] = 'a';
    $x[0] = 'c';
    
    echo json_encode($x);
    // {"2":"a","0":"c"}
    
    ksort($x);
    echo json_encode($x);
    // {"0":"c","2":"a"}
    

    If you want to pre-fill an array with a set number of null items, you can use array_fill. For instance:

    $x = array_fill(0, 5, null);
    $x[2] = 'a';
    echo json_encode($x);
    // [null,null,"a",null,null]
    

    You can also choose to add items "before" or "between" other elements, using array_splice with a length of 0:

    $x = ['a', 'b', 'c'];
    array_splice($x, 2, 0, 'NEW');
    echo json_encode($x);
    // ["a","b","NEW","c"]
    

    Positions past the current last position still just mean "add at end", though, they don’t create any "gaps":

    $x = ['a', 'b', 'c'];
    array_splice($x, 10, 0, 'END');
    echo json_encode($x);
    // ["a","b","c","END"]
    

    The other thing you can do is re-number the keys of an array, using array_values. That allows you to close gaps, but not create them:

    $x = [];
    $x[3] = 'three';
    $x[1] = 'one';
    $x[5] = 'five';
    
    echo json_encode( $x );
    // {"3":"three","1":"one","5":"five"}
    
    // Sort the items by their keys
    ksort($x);
    echo json_encode( $x );
    // {"1":"one","3":"three","5":"five"}
    
    // Close up the gaps
    $x = array_values($x);
    echo json_encode( $x );
    // ["one","three","five"]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search