5
$a = array("pear","apple","apple","ball","cat");
$u = array_unique($a);
echo json_encode($u);

The output appears as: {"0":"pear","1":"apple","3":"ball","4":"cat"}

I need a non-associative array as output as: ["apple","ball","cat","pear"].

3
  • 1
    Please tell why you need the non-associative array over the standard json-encoded one. The "problem" you're facing may be a non-issue really. Commented Jul 26, 2013 at 8:23
  • 1
    Then loop through your array and build a json string manually Commented Jul 26, 2013 at 8:23
  • 2
    @Ahmad: Building anything manually is usually a horrible idea, because people cannot be bothered to do it correctly. That's why we recommend json_encode, http_build_query, htmlspecialchars etc. Commented Jul 26, 2013 at 8:26

1 Answer 1

11

Reindex the array with array_values before encoding it:

echo json_encode(array_values($u));
Sign up to request clarification or add additional context in comments.

6 Comments

But that will be again the same array as before rite ? Correct me if I am wrong
@PrasanthBendra: No, it won't. But the result you get without is dependent on which duplicate elements array_unique chooses to remove, which is AFAIK not deterministic from a PHP userland perspective. If it removes the second "apple" you don't need to reindex, but if it removes the first you do. You can't control this, so reindexing is necessary to be safe.
Reindexing seems to be the only solution. It would have been easier if array_unique() allowed to make a choice whether or not to preserve original index value.
@smaske: What would be the point? It's extremely easy to reindex if you need to.
You should check stackoverflow.com/a/25296770/2393077 for explanation why it's happening
|

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.