Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A numeric string as array key in PHP

Tags:

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)
}
like image 677
Dogbert Avatar asked Nov 04 '10 19:11

Dogbert


People also ask

Can we convert string to array in PHP?

The str_split() is an inbuilt function in PHP and is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

What is numeric array in PHP?

Numeric arrays allow us to store multiple values of the same data type in a single variable without having to create separate variables for each value. These values can then be accessed using an index which in case of numeric arrays is always a number. Note: By default the index always starts at zero.

Is array key set PHP?

array is not set. This is also a predefined function in PHP which checks whether an index or a particular key exists in an array or not. It does not evaluate the value of the key for any null values. It returns false if it does not find the key in the array and true in all other possible cases.


8 Answers

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!
like image 193
Hamish Avatar answered Sep 22 '22 23:09

Hamish


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
like image 31
David Avatar answered Sep 24 '22 23:09

David


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';
like image 27
steampowered Avatar answered Sep 24 '22 23:09

steampowered


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.

like image 28
Undolog Avatar answered Sep 26 '22 23:09

Undolog


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:

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

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.

like image 33
bcosca Avatar answered Sep 24 '22 23:09

bcosca


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

like image 24
Brainfeeder Avatar answered Sep 23 '22 23:09

Brainfeeder


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.

WRONG

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);
            }
        break;
    }
    return null; // or trigger_error
}
like image 23
TarranJones Avatar answered Sep 25 '22 23:09

TarranJones


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"}
like image 32
GigiManco Avatar answered Sep 26 '22 23:09

GigiManco