Home > Enterprise >  Using the operator to combine arrays in PHP
Using the operator to combine arrays in PHP

Time:11-13

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?

CodePudding user response:

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

  • Related