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
Related Q & A:
- How to implement an openid in PHP?Best solution by Stack Overflow
- How to change javascript values to php?Best solution by stackoverflow.com
- How to show online users in PHP?Best solution by Stack Overflow
- How to read csv file using php?Best solution by Stack Overflow
- How can I check captcha with PHP?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.