DroidOS
DroidOS

Reputation: 8900

Why does json_encode() show keys after filtering with array_diff()?

The PHP documentation clearly states

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

This does not quite appear to be the case. Take the following example

$a = array(1,2,3,4);
$b = array(3,4,5);
echo "b FROM a = ";
echo json_encode(array_diff($a,$b));
echo "<br>a FROM b = ";
echo json_encode(array_diff($b,$a));

which returns

b FROM a = [1,2]
a FROM b = {"2":5}

i.e. a plain array in one case and an associative array in the other. Easily fixed - I only care about the values so I can simply do a array_values(array_diff. However, it bothers me that the documentation glosses over this difference. Perhaps someone here can shed more light on what is going on?

Upvotes: 1

Views: 469

Answers (1)

Mark Baker
Mark Baker

Reputation: 212452

It's not PHP that's doing anything magic, it's json

array_diff() maintains keys/associativity

b from a returns

array(
    0 => 1
    1 => 2
)

a from b returns

array(
    2 => 5
)

When you convert to json, the json doesn't bother with the keys if they are numeric from 0 and incrementing by 1, so the keys from b from a are ignored in the json, as they match that criteria

However, the key from the a from b result aren't naturally incrementing from 0, so they are stored in the json

If you don't want to maintain key associativity, use

echo json_encode(array_values(array_diff($b,$a)));

to reset the keys as naturally incrementing

Upvotes: 3

Related Questions