Home > Backend Development > PHP Tutorial > Can PHP Arrays Use Numeric Strings as Keys Without Integer Conversion?

Can PHP Arrays Use Numeric Strings as Keys Without Integer Conversion?

Barbara Streisand
Release: 2024-12-02 09:55:12
Original
903 people have browsed it

Can PHP Arrays Use Numeric Strings as Keys Without Integer Conversion?

Assigning String Integer Keys in PHP Arrays

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);
Copy after login

Here, you might expect the output to be:

array(1) {
  ["123"]=>
  int(1)
}
Copy after login

With the key '123' represented as a string. However, the actual output is:

array(1) {
  [123]=>
  int(1)
}
Copy after login

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!
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template