Array numeric string in PHP

Is it possible to use a digital string like "123" as a key in a PHP array without converting to an integer?

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

prints

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

I want to

 array(1) { ["123"]=> int(1) } 
+92
php
Nov 04 '10 at 19:30
source share
12 answers

No; no, it is not:

From the manual :

The key can be an integer or a string. If the key is a standard representation of an integer, it will be interpreted as such (i.e., "8" will be interpreted as 8, and "08" will be interpreted as "08").

Adding

Due to the comments below, I thought it would be interesting to note 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! 
+77
Nov 04 '10 at 20:00
source share
β€” -

Yes, this is possible using the cast array of the stdClass object:

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

This gives you (prior to PHP 7.1):

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

(Update: my original answer showed a more complex way using json_decode() and json_encode() , which is not needed.)

Pay attention to the comment . Unfortunately, it is not possible to directly refer to the value: $data['12'] will result in a notification.

Update :
From PHP 7.2, you can also use a numeric string as a key to refer to a value on it:

 var_dump( $data['12'] ); // int 32 
+37
03 Feb '16 at 15:03
source share

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

 $obj = new stdClass(); $key = '3'; $obj->$key = 'abc'; 
+11
Sep 19 '11 at 21:24
source share

My workaround:

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

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

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

You will see 55 as an int.

+8
Mar 14 '13 at 15:37
source share

You can give the keyword a string, but it will eventually be converted to an integer due to incorrect PHP input. See for yourself:

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

From the PHP manual:

The key can be an integer or a string. If the key is a standard representation of an integer, it will be interpreted as such (i.e., "8" will be interpreted as 8, and "08" will be interpreted as "08"). The floats in the key are truncated to the whole. Indexed and associative array types are the same type in PHP, which can contain both integer and string indexes.

+5
Nov 04 '10 at 19:59
source share

I had a problem with combining arrays in which there were both string and integer keys. It was important that the integers were also treated as a string, since they were the names of the input fields (as in shoe sizes, etc.).

When I used $data = array_merge($data, $extra); , PHP "reordered" the keys. When I tried to sort the whole keys (I tried using 6 - '6' - "6" even (string)"6" as keys) I got a rename from 0 to n ... If you think about it, in most cases this would be desirable behavior.

You can get around this using $data = $data + $extra; . Pretty straightforward, but I did not think about it at first ^^.

+1
Mar 20 '15 at 13:16
source share

Lines containing real integers will be passed to an integer type. For example. the key β€œ8” will actually be stored under 8. On the other hand, β€œ08” will not be selected, since it is not a valid decimal integer.

WRONG

I have a casting function that processes a sequential process for an associative array,

 $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 } 
+1
May 11 '16 at 16:36
source share

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

those. 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"} 
+1
Mar 30 '18 at 13:24
source share

I encountered this problem in an array with the keys "0" and "". This meant that I could not verify the keys of the array with == 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 use the array keys back to the strings before using.

 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"; } } 
0
Jan 22 '13 at
source share

As for the @david solution, note that when you try to access string values ​​in an associative array, numbers will not work. I assume they are cast integers behind the scenes (when accessing the array) and no value is found. Accessing integer values ​​will also not work. But you can use array_shift () to get the values ​​or iterate over the array.

 $data = new stdClass; $data->{"0"} = "Zero"; $data->{"1"} = "One"; $data->{"A"} = "A"; $data->{"B"} = "B"; $data = (array)$data; var_dump($data); /* Note the key "0" is correctly saved as a string: array(3) { ["0"]=> string(4) "Zero" ["A"]=> string(1) "A" ["B"]=> string(1) "B" } */ //Now let 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) 
0
Jun 02 '17 at 13:14
source share

This is possible by passing an array of array. Json_decode will respond with a valid indexed array.

 public function jsonSerialize() { $mappedArray = $this->toArray(); $response = []; foreach ($mappedArray as $item) { $response[] = [55 => $templateItem]; } return $response; } 
0
May 17 '19 at 8:49
source share

I had this problem when trying to sort an array in which I need a sort key that will be hex sha1. When the resulting sha1 value has no letters, PHP turns the key into an integer. But I needed to sort the array by relative row order. So I needed to find a way to make the key be a string without changing the sort order.

Looking at the ASCII chart ( https://en.wikipedia.org/wiki/ASCII ), the exclamation mark is sorted in much the same way as space, and, of course, below all numbers and letters,

So, I added an exclamation mark at the end of the key string.

 for(...) { $database[$sha.'!'] = array($sha,$name,$age); } ksort($database); $row = reset($database); $topsha = $row[0]; 
-one
Dec 23 '15 at 12:20
source share



All Articles