Which operator is used to create union of two arrays in PHP?

Disable ads (and more) with a premium pass for a one time $4.99 payment

Prepare for the Zend Certified PHP Engineer Exam with our comprehensive test, featuring flashcards and multiple choice questions. Each question comes with detailed hints and explanations. Ensure you're ready for your exam!

In PHP, the operator used to create the union of two arrays is the addition operator, represented by the plus sign. When you apply this operator between two arrays, it effectively combines the elements of both arrays without duplicating the values of the first array if they are also present in the second. If there are any string keys in the arrays, the values from the second array will overwrite those from the first in the case of key collisions.

For example, if you have two arrays like this:

$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("b" => "blueberry", "c" => "cherry");
$result = $array1 + $array2;

The result will be:

array("a" => "apple", "b" => "banana", "c" => "cherry");

In this case, the value "banana" from $array1 is retained, while "blueberry" from $array2 is ignored because of the existing key "b." Thus, the addition operator creates a union that preserves the values from the first array for any overlapping keys.

The other options represent comparison operators,

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy