A numeric string as array key in PHP

If you need to use a numeric key in a php data structure, an object will work. And objects preserve order, so you can iterate.

$obj = new stdClass();
$key = '3';
$obj->$key = 'abc';

Yes, it is possible by array-casting an stdClass object:

$data =  new stdClass;
$data->{"12"} = 37;
$data = (array) $data;
var_dump( $data );

That gives you (up to PHP version 7.1):

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

(Update: My original answer showed a more complicated way by using json_decode() and json_encode() which is not necessary.)

Note the comment: It's unfortunately not possible to reference the value directly: $data['12'] will result in a notice.

Update:
From PHP 7.2 on it is also possible to use a numeric string as key to reference the value:

var_dump( $data['12'] ); // int 32

My workaround is:

$id = 55;
$array = array(
  " $id" => $value
);

The space char (prepend) is a good solution because keep the int conversion:

foreach( $array as $key => $value ) {
  echo $key;
}

You'll see 55 as int.


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!

Tags:

Php