How to parse inner array in JSON response with PHP?

How do array keys work in PHP?

  • PHP is funny while handling the array keys. It auto increments the key value for enumerative Array but could not decide from where it should start assigning the key value. PHP starts from '0' that is ok but I could not find the exact logic for 4th array. Here is my sample code <?php echo '<pre>'; $arr = array('20', '0' => '21', '22'); print_r($arr); $arr1 = array('20', '1' => '21', '22'); print_r($arr1); $arr2 = array('18', '-1'=>'19', '20', '2' => '21', '22'); print_r($arr2); $arr3 = array('-1'=>'18', '19', '20', '1' => '21', '22'); print_r($arr3); ?>

  • Answer:

    There's nothing wrong with $arr3. The documentation states: The key is optional. If it is not specified, PHP will     use the increment of the largest previously used integer key. Since you used -1 as key, the next value will have zero as it's key, since zero is greater than any negative integer and also the lowest auto-indexing key value for any array. Notice that the second rule (zero being the lowest auto-indexing key value) trumps the first, so if you have an array such as: $a = array(-3 => 2, 8); The element with value 8 will be indexed as zero and not as -2 as one would think. Reference: http://docs.php.net/manual/en/language.types.array.php

Er Galvao Abbott at Quora Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.