Skip to content
Advertisement

A numeric string as array key in PHP

Is it possible to use a numeric string like "123" as a key in a PHP array, without it being converted to an integer?

$blah = array('123' => 1);
var_dump($blah);

prints

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

I want

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

Advertisement

Answer

No; no it’s not:

From the 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”).

Addendum

Because of the comments below, I thought it would be fun to point out that the behaviour is similar but not identical to JavaScript object keys.

foo = { '10' : 'bar' };

foo['10']; // "bar"
foo[10]; // "bar"
foo[012]; // "bar"
foo['012']; // undefined!
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement