Let's say I define an array:
$a = Array();
$a[0] = 1;
$a['0'] = 2;
$a['0a'] = 3;
print_r($a);
The output is fairly expected. I assume that there is some sort of strval()
or intval()
going on internally to allow the value to be overwritten.
Array
(
[0] => 2
[0a] => 3
)
But this is what confuses me.
foreach($a as $k => $v) {
print(gettype($k) . "\n");
}
This gives me:
integer
string
How is it that PHP internally makes those type conversions when using Array keys? i.e., How does it determine the key is a "valid decimal integer" as per the documentation? Also, is_int
doesn't work on strings.
All explained in the php manual
An array in PHP is actually an ordered map.
The key can either be an integer or a string.
A few typecasts are performed (even on strings)
Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
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.
Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.
Null will be cast to the empty string, i.e. the key null will actually be stored under "".
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
EDIT
If you want to know more about how PHP handles arrays internally, I recommend this article
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With