Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array key in php

Tags:

php

array-key

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, Thank You.

like image 667
user3562135 Avatar asked Feb 14 '23 02:02

user3562135


1 Answers

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.

like image 110
Marc B Avatar answered Feb 25 '23 12:02

Marc B