PHP Array with Numeric key or string type

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


array (size=2)
    '1' => int 1
    '2' => int 2

boolean false

boolean false

ERROR: E_NOTICE: Undefined offset: 1

ERROR: E_NOTICE: Undefined offset: 1

Now the issue is “How do I access these values”?

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

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

Which is the same as saying:

php > echo $obj->{'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};

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

php > echo array_key($obj, 2);

If you want array, set the second parameter of json_decode to true.

$a = json_decode('{"1":1,"2":2}', true);

when you cast a std object to array, numeric string key doesn’t cast to number. Here is an example.

$obj = new stdClass;
$obj->{'1'} = 1;
$arr = (array) $obj;
'Coz sharing is caring

By Swatantra Kumar

Swatantra is an Open Source evangelist, a technologist and researcher. Professionally, he does software development, software architecture, server administration and project management. When he's not writing software, he enjoys building web entities and servers, reading about and working with new technologies, and trying to get his friends to make the move to open source software. He's written, co-written and published many articles in international journals, on various domains/topics including Open Source, Networks, Computer Organization, Mobile Technologies, and Business Intelligence. He made a proposal for an information management system at University level during graduation days.

One reply on “PHP Array with Numeric key or string type”

Neat blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple tweeks would really make my blog stand out. Please let me know where you got your theme. Cheers

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.