1

I've recently discovered that + may be used to combine arrays in PHP.

Add an associative array to an associative array:

$array1 = ["The" => "quick", "brown" => "fox"];
$array2 = ["jumps" => "over", "the" => "lazy dog"];

$combinedArray = $array1 + $array2;

/* Gives:

Array
(
    [The] => quick
    [brown] => fox
    [jumps] => over
    [the] => lazy dog
)

*/

Add an associative array to an indexed array:

$array1 = ["The", "quick", "brown", "fox"];
$array2 = ["jumps" => "over", "the" => "lazy dog"];

$combinedArray = $array1 + $array2;

/* Gives:

Array
(
    [0] => The
    [1] => quick
    [2] => brown
    [3] => fox
    [jumps] => over
    [the] => lazy dog
)

*/

Add an indexed array to an associative array:

$array1 = ["The" => "quick", "brown" => "fox"];
$array2 = ["jumps", "over", "the", "lazy dog"];

$combinedArray = $array1 + $array2;

/* Gives:

Array
(
    [The] => quick
    [brown] => fox
    [0] => jumps
    [1] => over
    [2] => the
    [3] => lazy dog
)

*/

Add an indexed array to an indexed array:

$array1 = ["The", "quick", "brown", "fox"];
$array2 = ["jumps", "over", "the", "lazy dog"];

$combinedArray = $array1 + $array2;

/* Gives:

Array
(
    [0] => The
    [1] => quick
    [2] => brown
    [3] => fox
)

*/

One of these is not like the others.

Why isn't the last one working?

3
  • 1
    From the docs "for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored" Commented Nov 13, 2021 at 10:54
  • 2
    Because of the same indexes. Change "the" => "lazy dog" to "The" => "lazy dog" in your first example and see what the result is Commented Nov 13, 2021 at 10:54
  • 2
    For the last one , Try to use + on two arrays of different sizes (left hand one: 4 elements), (right hand one: 5 elements) and see what happens Commented Nov 13, 2021 at 10:55

1 Answer 1

3

This happens because both arrays in the last example have the same keys:

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Docs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.