1

So I just stumbled upon this issue with array conversion to JSON and back to array. I used the function to store the array in database.

Code:

$array = array(
    1 => 'first',
    '200'  => 'second'
);
$array = json_encode($array);
$array = json_decode($array);
$array = (array)$array;

echo "<pre>"; var_dump($array);
var_dump(array_key_exists(1, $array));
var_dump(array_key_exists(200, $array));
var_dump(array_key_exists('1', $array));
var_dump(array_key_exists('200', $array));

Output:

array(2) {
  ["1"]=>
  string(5) "first"
  ["200"]=>
  string(6) "second"
}
bool(false)
bool(false)
bool(false)
bool(false)

Any explanation? Solution? Thanks?

1
  • @PaulCrovella so, there's no workaround for this in previous version? I'm working on this ancient website and would mess things up if I update PHP version just for this. :) Commented Oct 26, 2018 at 4:06

1 Answer 1

2

Instead of

$array = json_encode($array); $array = json_decode($array); $array = (array)$array;

you only need to add a parameter to convert to array in json_decode

$encoded_array = json_encode($array); $array = json_decode($encoded_array, true);

See documentation about json_decode() in http://php.net/manual/en/function.json-decode.php

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

1 Comment

Like a glove! (not sure if im using the expression correctly). Thanks

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.