Home >Backend Development >PHP Tutorial >Can PHP Arrays Use Numeric Strings as Keys Without Integer Conversion?
Using a PHP array usually involves assigning values to keys that are either strings or integers. However, the question arises: Can we use numeric strings as array keys without PHP converting them to integers? Consider the following example:
$blah = array('123' => 1); var_dump($blah);
Here, you might expect the output to be:
array(1) { ["123"]=> int(1) }
With the key '123' represented as a string. However, the actual output is:
array(1) { [123]=> int(1) }
This demonstrates that the numeric string '123' has been converted to an integer key 123.
Why Doesn't PHP Allow Numeric String Keys?
According to the PHP manual:
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08").
This means that PHP interprets any numeric string as an integer, even if you quote it as a string.
Addendum: Comparison to JavaScript Object Keys
This behavior in PHP is similar but not identical to JavaScript object keys. In JavaScript, you can use numeric strings as object keys, and they will retain their string form:
foo = { '10' : 'bar' }; foo['10']; // "bar" foo[10]; // "bar" foo[012]; // "bar" foo['012']; // undefined!
In this example, '10' is used as a string key, while 10 and 012 are both interpreted as integers. However, '012' as a quoted string is treated as undefined, unlike in PHP where it would be interpreted as the string "012".
The above is the detailed content of Can PHP Arrays Use Numeric Strings as Keys Without Integer Conversion?. For more information, please follow other related articles on the PHP Chinese website!