I have the following code:
$myAwesomeArray = array(
'value1',
'value2',
'value3',
'value3',
'value4',
'value4'
);
$z = json_encode(array('all' => $myAwesomeArray));
var_dump('before', $z);
$myAwesomeArray = array_unique($myAwesomeArray);
$z = json_encode(array('all' => $myAwesomeArray));
var_dump('after', $z);
So there is an array implicitly indexed by integer keys which contains some duplicate values. It's important to have duplicate values, otherwise the behaviour described below will not occur.
As you can see, I convert in JSON both the array and the result of passing it through array_unique() function.
The output I expect to see is something like:
string(6) "before"
string(63) "{"all":["value1","value2","value3","value3","value4","value4"]}"
string(5) "after"
string(45) "{"all":["value1","value2","value3","value4"]}"
However I see this instead:
string(6) "before"
string(63) "{"all":["value1","value2","value3","value3","value4","value4"]}"
string(5) "after"
string(61) "{"all":{"0":"value1","1":"value2","2":"value3","4":"value4"}}"
Apparently the function does indeed remove the duplicate values, but it changes the keys from integers to strings, at least that's what json_encode() sees them.
Another weird behaviour is that if, after passing the array through array_unique(), I do this:
var_dump(array_keys($myAwesomeArray));
then the printed are marked with type int in the output:
array(4) {
[0]=> int(0)
[1]=> int(1)
[2]=> int(2)
[3]=> int(4)
}
which does not match with what json_encode() is outputting.
I read everything I could find about array_unique() and can't figure out why this happens.
I tested the code above on a Windows 7 machine using PHP 5.3 and PHP 5.6 with no difference in behaviour/output.
Is this a bug? Should I report it as such? Or is this normal behaviour?
array_valuesto reindex it.array_unique()to see what's going on, maybe it's intentional behaviour.3), thus you get an object.