简体   繁体   中英

How does PHP internally use array keys and types?

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? ie, 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. Eg 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. Eg the key 8.7 will actually be stored under 8.

Bools are cast to integers, too, ie the key true will actually be stored under 1 and the key false under 0.

Null will be cast to the empty string, ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM