Array_unique - odd behavior

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I've just spent the last few hours tracking down an obscure bug and
distilled it down to a simple test script that highlights the problem.

There are some really strange interactions going on between the php
functions array_unique and json_encode:

In the following example there are 3 arrays, with the same strings, in
different orders.

I create unique versions of these arrays, convert them to json and
print the output.

For the first 2 arrays I get the expected output as a json array:

However the 3rd array gets converted to a json object with numbered

Even though inspection with a debugger shows $u3 is indeed a php array
right before the conversion!

This is obviously breaking a lot of my javascript when this happens...
Is this a bug in php? I'm using version 5.2.8 Any idea what is going
on and/or how to work around?

Thanks for any help.




echo "<p>u1: ";
echo json_encode($u1);
echo "</p>";

echo "<p>u2: ";
echo json_encode($u2);
echo "</p>";

echo "<p>u3: ";
echo json_encode($u3);
echo "</p>";


Re: Array_unique - odd behavior

Mark Smith wrote:
Quoted text here. Click to load it

That is correct behavior.  array_unique() will delete duplicate values,
but will not reindex the array.  So, after calling array_unique on each,
you get:

$u1: Array
     [0] => pear
     [1] => apple
     [0] => apple
     [1] => pear
     [0] => apple
     [2] => pear

When array elements are sequentially numbered from zero, the index is
not needed in json.  However, $u3 is no longer in sequence, so array
indexes are required.

Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.

Re: Array_unique - odd behavior

Quoted text here. Click to load it

Very good, thats 2 subtleties from 2 php functions interacting in a
way I would not expect! An optional flag for either array_unique or
json_encode to reindex the array would have made this easier for a
novice like me to track down. But now I know whats going on array_merge
(array_unique($a)) works just as well.


Re: Array_unique - odd behavior

Quoted text here. Click to load it

Jerry has pointed out the reason. Here is the fix:


Re: Array_unique - odd behavior

Quoted text here. Click to load it

Or of course you could use:

Site Timeline