$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
First of all we must write those dictionaries as they really are; the form above is "condensed", with implicit numeric keys.
$array1 is a: green, 0: red, 1: blue
$array2 is b: green, 0: yellow, 1: red
Now array_intersect
checks what values are common. They are green, and red. The corresponding items from array1 are taken:
a: green
0: red
and so you have two keys, 'a' and 0, mapped to green and red respectively.
At this point I'll add that mixing numeric and non-numeric keys is a recipe for disaster, unless you're incredibly careful about what you're doing; lots of PHP functions will not preserve keys and renumber the values converting dictionaries to arrays.
And as you have seen, it's not immediate to tell an array from a dictionary. To add to the risk, JSON encoding is completely different for the two, so a tiny change in a structure might make a Web service conversation to abruptly collapse.
JSON
This is my favourite parlor trick.
$arr = array( 'Hello', 'World' );
This JSON-encodes, as you would expect, to:
[ 'Hello', 'World' ]
Let's say I delete the last element and re-JSON:
[ 'Hello' ]
But let's say I delete an element that is not the last. What does PHP do? It removes the element and the key, but does not renumber the array. The array has now a hole. And arrays don't have holes -- dictionaries do.
So this is now a dictionary. And in JSON it suddenly becomes:
{ "1": "World" }
Which means that this example code is subtly bugged:
$arr = functionReturningArrayOfElements();
if (-1 != $killThisElement) {
unset($arr[$killThisElement]);
}
header('Content-Type: application/json');
die(json_encode($arr));
When $killThisElement
is the very last entry ($count($arr)-1), then the JSON will be encoded as an array. Otherwise, it will be encoded as a dictionary.
Before returning, I need to be sure of what I return:
$arr = array_values($arr); // This renumbers the keys, forcing it to always be an array
or
$arr['count'] = count($arr);
// This adds a non-numeric key, forcing $arr to always be a dictionary.
// The extra key is called 'count' just so it makes sense, but it is also
// a BAD IDEA, since it encourages to loop through the object instead of
// using the proper Javascript Object methods. A better choice from this
// point of view would be
$arr['comment'] = 'This is a dictionary.';