PHP also lets us combine arrays. The union (
+) operator takes two array operands and returns a new array with any unique keys from the second array appended to the first array.
$my_array = ["panda" => "very cute", "lizard" => "cute", "cockroach" => "not very cute"]; $more_rankings = ["capybara" => "cutest", "lizard" => "not cute", "dog" => "max cuteness"]; $animal_rankings = $my_array + $more_rankings;
$animal_rankings we created above will have each of the key=>value pairs from
$my_array. In addition, it will contain the key=>value pairs from
"max cuteness". However, since
"lizard" is not a unique key,
$animal_rankings["lizard"] will retain the value of
$my_array["lizard"] (which is
The union operator can be a little tricky… consider the following union:
$number_array = [8, 3, 7]; $string_array = ["first element", "second element", "third element"]; $union_array = $number_array + $string_array;
What values does
$union_array hold? It has the elements
7. Since the two arrays being joined have identical keys (
2), no values from the second array,
$string_array, are included in
Let’s get some practice!
All the animals are throwing a potluck party! Generous Giraffe is bringing an assortment of foods—recorded in the
$giraffe_foods array. Industrious Impala is bringing a bunch of food as well (
Using the union operator (
+), create an array,
$potluck representing all the food that will be brought by these two animals!
print_r() to print the
$potluck array to the terminal.
Uh oh. Who invited Redundant Rat? Redundant Rat is bringing a lot of food types that have already been accounted for… Only one item from
$rat_foods would be added to the
$potluck array if it were joined to it. Can you tell which one?
It’s not required, but you might try joining the arrays in different orders and printing the results to see what’s going on! Otherwise, just click “Run” to continue.