phparraysarray-key

How does PHP determine the key to use if I declare array elements without offering explicit keys?


I'm 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));
?> 

Output:

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

I'm wondering why [4] => 2 and why [5] => 3. I thought it would be [4] => 4 and [5] => 5 because they are both at index 4 and 5. I'm slightly confused as to what exactly is going on in this array, if possible could someone point me in the right direction.


Solution

  • You're mixing keyed with keyless array entries, so it gets a bit wonky:

    $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 don't provide a key, PHP will assign one, starting at 0. If the potential new key would conflict with one already assigned, that potential key will be skipped until PHP finds one that CAN be used.