Doc #80295 [Opn]: + operator on arrays is documented as Union but it's not

From: Date: Thu, 29 Oct 2020 23:32:21 +0000
Subject: Doc #80295 [Opn]: + operator on arrays is documented as Union but it's not
References: 1  Groups: php.doc.bugs 
Request: Send a blank email to doc-bugs+get-18054@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=80295&edit=1

 ID:                 80295
 Updated by:         requinix@php.net
 Reported by:        rimas at kudelis dot lt
 Summary:            + operator on arrays is documented as Union but it's
                     not
 Status:             Open
 Type:               Documentation Problem
-Package:            Documentation problem
+Package:            Arrays related
 PHP Version:        Irrelevant
 Block user comment: N
 Private report:     N

 New Comment:

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).
https://3v4l.org/dXl11

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.
https://3v4l.org/SuAln


Previous Comments:
------------------------------------------------------------------------
[2020-10-29 13:53:17] rimas at kudelis dot lt

Description:
------------
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?



------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=80295&edit=1


Thread (3 messages)

« previous php.doc.bugs (#18054) next »