"mike", 4, 5, 10=>-2.3); print_r(array_...">

Array key in php

I am trying to understand this code:

<?php 

$list = array(-10=>1, 2, 3, "first_name"=>"mike", 4, 5, 10=>-2.3); 

print_r(array_keys($list));
?> 

Conclusion:

Array ( [0] => -10 [1] => 0 [2] => 1 [3] => first_name [4] => 2 [5] => 3 [6] => 10 ) 

I am wondering why [4] => 2 and why [5] => 3I thought it would be [4] => 4 and [5] => 5because they are both at index 4 and 5. I am a little confused as to what exactly is happening in this array, if possible, someone can point me in the right direction, thanks.

+4
source share
5 answers

You mix the key with the keys without the key, so it becomes a little awkward:

$list = array(
    -10 => 1   // key is -10
        => 2  // no key given, use first available key: 0
        => 3  // no key given, use next available key: 1
    "first_name" => "mike" // key provided, "first_name"
        => 4  // no key given, use next available: 2
        => 5  // again no key, next available: 3
     10 => -2.3  // key provided: use 10

If you do not provide a key, PHP will assign it starting at 0. If a potential new key conflicts with an already assigned one, this potential key will be skipped until PHP finds one that MAY be used.

+6

:

$list = array(-10=>1, 2 => null, 3=> null, "first_name"=>"mike", 4=> null, 5=> null, 10=>-2.3);

, , 2, 3, 4 5

+1

, PHP .

$list = array(-10=>1, 2, 3, "first_name"=>"mike", 4, 5, 10=>-2.3); 

2,3,4,5, .

So ==> [0] => 2, [1] => 3, [2] => 4, and [3] => 5.

+1
source

In your array you mix key => valueonly with value.

-10 is your first key. Then, since you do not define a key for the following items, it is automatically assigned in order.

0
source

It appears that when the key is not set, array_keys saves the track of the last assigned key and assigns a serial number:

array(7) {
  [0]=>
  int(-10)
  [1]=>
  int(0)   // first without key (starting on 0)
  [2]=>
  int(1)   // second without key
  [3]=>
  string(10) "first_name"
  [4]=>
  int(2)  // third without key 
  [5]=>
  int(3)  // fourth without key
  [6]=>
  int(10)
}
0
source

Source: https://habr.com/ru/post/1539019/


All Articles