Back to questions
JuniorTheoryCommon
What does the program print?
<?php
$a = [1, 2];
$b = [3];
$c = ['x' => 1];
$d = ['x' => 2, 'y' => 3];
echo json_encode(array_merge($a, $b)), ' ', json_encode($a + $b), ' ';
echo json_encode($c + $d), ' ', json_encode([...$a, ...$b]), "\n";[1,2,3] [1,2] {"x":1,"y":3} [1,2,3]
- Expecting
$a + $bto append one list to another:+keeps every key of the left array and adds only missing keys, so[1, 2] + [3]is[1, 2]. - Expecting the right side of
+to win on a repeated string key, as inarray_merge:+keeps the left value, so'x'stays1.
- How would you combine two arrays whose integer keys are ids that must survive?
- What does
array_mergedo when both arrays have the key'x'?