0

I have state list in JSON format and i am using json_decode function but when i am trying to access array values getting error.

$states='{
    "AL": "Alabama",
    "AK": "Alaska",
    "AS": "American Samoa",
    "AZ": "Arizona",
    "AR": "Arkansas"

}';

$stateList = json_decode($states);
echo $stateList['AL'];

Fatal error: Cannot use object of type stdClass as array on line 65

1

4 Answers 4

3

You see, the json_decode() method doesn’t return our JSON as a PHP array; it uses a stdClass object to represent our data. Let’s instead access our object key as an object attribute.

echo $stateList->AL;

If you provide true as the second parameter to the function we will receive our PHP array exactly as expected.

$stateList = json_decode($states,true);
echo $stateList['AL'];
Sign up to request clarification or add additional context in comments.

Comments

3

Either you pass true to json_decode like Nanhe said:

$stateList = json_decode($states, true);

or change the way you access it:

echo $stateList->{'AL'};

Comments

0

You could pass true as the second parameter to json_encode or explicitly convert the class to array. I hope that helps.

Comments

0
 $stateList = json_decode($states);
 //statelist is a object so you can not access it as array
 echo $stateList->AL;

If you want to get an array as a result after decode :

  $stateList = json_decode($states, true);
 //statelist is an array so you can not access it as array
 echo $stateList['AL'];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.