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.
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.
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)
}