0

I find a weird result of json_encode today in my production code, sometimes it returns an array, like ["perl","php","python"], but sometimes an object, like {"0":"perl","2":"python"}. Here is a minimal example:

$a = array("perl", "php", "python", "something other");
foreach($a as $index => $item) 
{
    if ($item == "something")
        unset($a[$index]);
}
echo json_encode($a);

Why does this happen?

3
  • 1
    Why are you answering to yourself? Commented Apr 26, 2015 at 13:32
  • 2
    It's a Q&A-style, hope others can benefit from my experience. see here Commented Apr 26, 2015 at 13:37
  • Sorry about that, I didn't know this thing...sorry! Commented Apr 26, 2015 at 13:41

1 Answer 1

2

In the foreach loop, once $item == "something" is true, the array keys are not consecutively numerically indexed (except last iteration), then json_encode returns an object. If all the values in the array are not equal to "something", it returns an array. Since array is always what I want, I use array_values() before json_encode.

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

1 Comment

Why are you answering to yourself?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.