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);


array(1) {

I want

array(1) {

Solution 1

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").


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!

Solution 2

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) {

(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.

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

Solution 3

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.

Solution 4

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';

Solution 5

You can typecast the key to a string but it will eventually be converted to an integer due to PHP's loose-typing. See for yourself:


From 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"). Floats in key are truncated to integer . The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

Solution 6

I had this problem trying to merge arrays which had both string and integer keys. It was important that the integers would also be handled as string since these were names for input fields (as in shoe sizes etc,..)

When I used $data = array_merge($data, $extra); PHP would 're-order' the keys. In an attempt doing the ordering, the integer keys (I tried with 6 - '6'- "6" even (string)"6" as keys) got renamed from 0 to n ... If you think about it, in most cases this would be the desired behaviour.

You can work around this by using $data = $data + $extra; instead. Pretty straight forward, but I didn't think of it at first ^^.

Solution 7

Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.


I have a casting function which handles sequential to associative array casting,

$array_assoc = cast($arr,'array_assoc');

$array_sequential = cast($arr,'array_sequential');

$obj = cast($arr,'object');

$json = cast($arr,'json');

function cast($var, $type){

    $orig_type = gettype($var);

    if($orig_type == 'string'){

        if($type == 'object'){
            $temp = json_decode($var);
        } else if($type == 'array'){
            $temp = json_decode($var, true);
        if(isset($temp) && json_last_error() == JSON_ERROR_NONE){
            return $temp;
    if(@settype($var, $type)){
        return $var;
    switch( $orig_type ) {

        case 'array' :

            if($type == 'array_assoc'){

                $obj = new stdClass;
                foreach($var as $key => $value){
                    $obj->{$key} = $value;
                return (array) $obj;

            } else if($type == 'array_sequential'){

                return array_values($var);

            } else if($type == 'json'){

                return json_encode($var);
    return null; // or trigger_error

Solution 8

As workaround, you can encode PHP array into json object, with JSON_FORCE_OBJECT option.

i.e., This example:

     $a = array('foo','bar','baz');
     echo "RESULT: ", json_encode($a, JSON_FORCE_OBJECT);

will result in:

     RESULT: {"0" : "foo", "1": "bar", "2" : "baz"}

Solution 9

I ran into this problem on an array with both '0' and '' as keys. It meant that I couldn't check my array keys with either == or ===.

$array=array(''=>'empty', '0'=>'zero', '1'=>'one');
echo "Test 1\n";
foreach ($array as $key=>$value) {
    if ($key == '') { // Error - wrongly finds '0' as well
        echo "$value\n";
echo "Test 2\n";
foreach ($array as $key=>$value) {
    if ($key === '0') { // Error - doesn't find '0'
        echo "$value\n";

The workaround is to cast the array keys back to strings before use.

echo "Test 3\n";
foreach ($array as $key=>$value) {
    if ((string)$key == '') { // Cast back to string - fixes problem
        echo "$value\n";
echo "Test 4\n";
foreach ($array as $key=>$value) {
    if ((string)$key === '0') { // Cast back to string - fixes problem
        echo "$value\n";

Solution 10

Regarding @david solution, please note that when you try to access the string values in the associative array, the numbers will not work. My guess is that they are casted to integers behind the scenes (when accessing the array) and no value is found. Accessing the values as integers won't work either. But you can use array_shift() to get the values or iterate the array.

$data = new stdClass;
$data->{"0"} = "Zero";
$data->{"1"} = "One";
$data->{"A"} = "A";
$data->{"B"} = "B";

$data = (array)$data;

Note the key "0" is correctly saved as a string:
array(3) {
  string(4) "Zero"
  string(1) "A"
  string(1) "B"

//Now let's access the associative array via the values 
//given from var_dump() above:
var_dump($data["0"]); // NULL -> Expected string(1) "0"
var_dump($data[0]); // NULL (as expected)
var_dump($data["1"]); // NULL -> Expected string(1) "1"
var_dump($data[1]); // NULL (as expected)
var_dump($data["A"]); // string(1) "A" (as expected)
var_dump($data["B"]); // string(1) "B" (as expected)

Solution 11

I had this problem while trying to sort an array where I needed the sort key to be a hex sha1. When a resulting sha1 value has no letters, PHP turns the key into an integer. But I needed to sort the array on the relative order of the strings. So I needed to find a way to force the key to be a string without changing the sorting order.

Looking at the ASCII chart ( the exclamation point sorts just about the same as space and certainly lower than all numbers and letters.

So I appended an exclamation point at the end of the key string.

for(...) {

    $database[$sha.'!'] = array($sha,$name,$age);

$row = reset($database);
$topsha = $row[0];