0

I am studying PHP and came across a question like this:

What is the output of the following array?

Code:

$a = array(0.001 => 'b', .1 => 'c');
print_r($a);

The answer is 0 => 'c' - now I know array keys can't be numbers but wouldn't that throw an error? Why is the first element overwritten?

halfer
  • 19,824
  • 17
  • 99
  • 186
Stereo99
  • 234
  • 1
  • 9
  • 2
    From the [PHP manual documentation](http://php.net/manual/en/language.types.array.php): "*Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.*". Here both your keys, when their fractional prats are truncated, equals `0`. An array can't have duplicate keys, so whenever you define a new value with a key that already exists, it overwrites the previous value. – Amal Murali May 24 '14 at 15:20

1 Answers1

2

From the documentation on arrays:

Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.

and, as Alex points out below:

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • 1
    Regarding "Why is the first element overwritten?", also from the docs: `If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten. ` – Alex Shesterov May 24 '14 at 15:20