Coder Perfect

In PHP, a numeric string is used as an array key.

Problem

Is it possible to use a numeric string as a key in a PHP array without converting it to an integer?

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

prints

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

I want

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

Asked by Dogbert

Solution #1

No, no, no, no, no, no, no, no, no, no, no, no

From the manual:

Addendum

Because of the comments below, I thought it might be interesting to note out that the behavior is similar but not identical to JavaScript object keys.

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

foo['10']; // "bar"
foo[10]; // "bar"
foo[012]; // "bar"
foo['012']; // undefined!

Answered by Hamish

Solution #2

Yes, array-casting a stdClass object is possible:

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

This offers you the following (up to PHP 7.1):

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

(Update: My initial response suggested a more difficult method that did not require the use of json decode() and json encode().)

It’s worth noting the comment: It’s not feasible to directly reference the value: A notification will be generated if $data[’12’] is used.

Update: Starting with PHP 7.2, you may also use a numeric string as the key to refer to the value:

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

Answered by David

Solution #3

An object will work if you need to use a number key in a php data structure. And items keep their order, allowing you to iterate.

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

Answered by steampowered

Solution #4

My workaround is:

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

Because the int conversion is kept, the space char (prepend) is a good solution:

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

Integer 55 is what you’ll see.

Answered by Undolog

Solution #5

You can typecast the key to a string, but owing to PHP’s loose typing, it will eventually be transformed to an integer. Check it out for yourself:

$x=array((string)123=>'abc');
var_dump($x);
$x[123]='def';
var_dump($x);

According to the PHP manual:

Answered by bcosca

Post is based on https://stackoverflow.com/questions/4100488/a-numeric-string-as-array-key-in-php