Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does PHP internally use array keys and types?

Tags:

php

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.

like image 384
Phil Avatar asked Jan 30 '13 18:01

Phil


1 Answers

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

like image 168
Michel Feldheim Avatar answered Oct 22 '22 15:10

Michel Feldheim