user3562135
user3562135

Reputation: 159

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.

Upvotes: 4

Views: 109

Answers (5)

Teknotica
Teknotica

Reputation: 1136

It seems like when the key is not set, array_keys keeps the track of the last key assigned and will assign the consecutive 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)
}

Upvotes: 0

alexmngn
alexmngn

Reputation: 9587

In your array, you are mixing key => value with just value.

-10 is your first key. Then because you are not defining a key for following items, it's automatically assigned in order.

Upvotes: 0

Dev&#39;Hamz
Dev&#39;Hamz

Reputation: 488

It's normal because PHP is waiting for a key.

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

And you don't give him in 2,3,4,5 so it gives a key automatic .

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

Upvotes: 1

ekans
ekans

Reputation: 1714

try this:

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

to have the result you want so 2, 3, 4 and 5 will be count as key instead of value

Upvotes: 1

Marc B
Marc B

Reputation: 360572

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.

Upvotes: 6

Related Questions