Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array with numeric keys as string can't be used [duplicate]

Tags:

json

arrays

php

I have a PHP array that has numeric keys as a string type.

But when I try and access them PHP is giving me an undefined index error.

$a = (array)json_decode('{"1":1,"2":2}'); var_dump($a); var_dump(isset($a[1])); var_dump(isset($a["1"])); var_dump($a[1]); var_dump($a["1"]); 

Output:

 array (size=2)     '1' => int 1     '2' => int 2  boolean false  boolean false  ERROR: E_NOTICE: Undefined offset: 1  null  ERROR: E_NOTICE: Undefined offset: 1  null 

How do I access these values?

Demo: http://codepad.viper-7.com/8O03IM

like image 807
Petah Avatar asked Jul 17 '12 03:07

Petah


People also ask

Can PHP arrays have duplicate keys?

Arrays contains unique key. Hence if u are having multiple value for a single key, use a nested / multi-dimensional array. =) thats the best you got.

Can associative array have same key?

No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.

How to unique array in php?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.

What is array_keys () used for in PHP?

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


1 Answers

So, I haven't seen any other answers touch upon this, but @xdazz came close.

Let's start our environment, $obj equals the object notation of a decoded string:

php > $obj = json_decode('{"1":1,"2":2}');  php > print_r($obj); stdClass Object (     [1] => 1     [2] => 2 )  php > var_dump( $obj ); object(stdClass)#1 (2) {   ["1"]=>   int(1)   ["2"]=>   int(2) } 

If you want to access the strings, we know the following will fail:

php > echo $obj->1;  Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `'{'' or `'$'' in php shell code on line 1 

Accessing the object variables

You can access it like so:

php > echo $obj->{1}; 1 

Which is the same as saying:

php > echo $obj->{'1'}; 1 

Accessing the array variables

The issue with arrays is that the following return blank, which is the issue with typecasting.

php > echo $obj[1]; php > 

If you typecast it back, the object is once again accessible:

php > $obj = (object) $obj; php > echo $obj->{1}; 1 

Here is a function which will automate the above for you:

function array_key($array, $key){     $obj = (object) $array;     return $obj->{$key}; } 

Example usage:

php > $obj = (array) $obj; php > echo array_key($obj, 1); 1  php > echo array_key($obj, 2); 2 
like image 112
Mike Mackintosh Avatar answered Sep 28 '22 03:09

Mike Mackintosh