0

I decoded a json string and then Type casted it into any Array and tried to access it later. But it generate Undefined Index Error

Here is my sample code

$json = '{"1":"Active","0":"Inactive"}'; //Yes, it is a valid Json String
$decodedObject = json_decode($json);
$array = (array)$decodedObject;
echo $array['1']; // This generates undefinded Index 1 Error

Here is the display of the array and object

stdClass Object
(
    [1] => Active
    [0] => Inactive
)

Array
(
    [1] => Active
    [0] => Inactive
)
1
  • Just do var_dump with $array and look what you've got. Commented Mar 27, 2011 at 8:26

2 Answers 2

1

1.) instead of making it in two steps how about doing it like:

$decodedArray = json_decode($json, true);

it will directly give you the array instead of object

2.) make sure your json code is corret:

{"1":"Active","0":"Inactive"}

3.) your var_dump shows that array{[1]=>.... so why refering it like $array['1'] can it be even simpler $array[1]

Sign up to request clarification or add additional context in comments.

1 Comment

wow, this fixed everything. I will accept it in five minute :D Thanks
1

No, it is not a valid JSON string (JSONLint is your friend). You used a comma instead of a colon:

{"1":"Active","0","Inactive"} // invalid
{"1":"Active","0":"Inactive"} // valid

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.