|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #80295 + operator on arrays is documented as Union but it's not
Submitted: 2020-10-29 13:53 UTC Modified: 2020-10-29 23:32 UTC
From: rimas at kudelis dot lt Assigned:
Status: Open Package: Arrays related
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2020-10-29 13:53 UTC] rimas at kudelis dot lt
The documentation for array operators currently says this:

> $a + $b 	Union 	Union of $a and $b.

At least to me, this signals that if I apply this operator on two arrays (e.g. [1, 2] and [3, 4, 5, 6]), I would get an array which holds all elements appearing in each array: [1, 2, 3, 4, 5, 6]. But that's not what I get. Instead, I get [1, 2, 5, 6], as documented in a note below the initial table:

> 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. 

as well as in a set of examples below.

I believe it's wrong to refer to this operation as simply union, thus I suggest to change the documentation to make it more obvious upfront.

I don't have a good idea how to reword it exactly ATM, but perhaps just changing "Union" to "Union by keys" in the table would be enough?


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2020-10-29 23:32 UTC]
-Package: Documentation problem +Package: Arrays related
 [2020-10-29 23:32 UTC]
Personally, I would avoid the term "union" entirely. It's too misleading.

I think of + for arrays as a "fill in the blanks" operator. Or a "with defaults" operator. The LHS is the base array, and the RHS will provide additional values for the keys that do not exist in the base array.

Essentially, $a + $b is equivalent to array_replace($b, $a).

Note that's array_replace and not array_merge, and that the arguments are backwards from how they're used in the operator.

The primary use case for me has been about dealing with missing/optional data from an associative array: take the provided values and "fill in" what wasn't given from a set of defaults.
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Thu Sep 23 14:03:43 2021 UTC