0
$arr = array();
$arr[0] = "2a123";
$arr[1] = "2123";
$arr["other_option"] = "2123";

var_dump($arr);

$arr = json_encode($arr);

$arr = (array)json_decode($arr);

var_dump($arr);

var_dump( $arr[1]);
var_dump( $arr["1"]);

The output of 2 last var_dump are NULL NULL, if we remove the 4th line $arr["other_option"] = "2123"; it'll ouput correctly, but I don't understand why!

3
  • What is the output of var_dump($arr);? Commented Aug 10, 2012 at 9:27
  • 1
    TIP : try json_decode($json, true) instead of type casting using (array) Commented Aug 10, 2012 at 9:27
  • The TIP of diEcho works like a charm, but I still don't understand why, is it a PHP bug in type casting? Commented Aug 10, 2012 at 9:32

1 Answer 1

2

instead of type casting to array , set true in json_encode

When TRUE, returned objects will be converted into associative arrays.

$arr = array();
$arr[0] = "2a123";
$arr[1] = "2123";
$arr["other_option"] = "2123";
$arr = json_encode($arr);   
$arr = json_decode($arr,true);
var_dump( $arr['other_option']); // return 2123

working DEMO

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

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.