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;
The $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 $more_rankings
: "capybara"
=>"cutest"
and "dog"
=>"max cuteness"
. However, since "lizard"
is not a unique key, $animal_rankings["lizard"]
will retain the value of $my_array["lizard"]
(which is "cute"
).
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 8
, 3
, and 7
. Since the two arrays being joined have identical keys (0
, 1
, and 2
), no values from the second array, $string_array
, are included in $union_array
.
Let’s get some practice!
Instructions
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 ($impala_foods
).
Using the union operator (+
), create an array, $potluck
representing all the food that will be brought by these two animals!
Use 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.