I've been working at a new job and the interesting thing when working with other people's code is you often learn a heap of stuff you didn't already know. A couple of weeks ago I came across a way to merge arrays in PHP with the + operator, instead of using the array functions (e.g. array_merge) so share this here.
Example
The easiest way to illustrate this is with an example.
Using the plus operator to merge an array really works best with an associative array, otherwise it merges on the numbered indexes, which can lead to some unexpected or odd results.
Here's a couple of arrays, with some intersecting elements and some different elements.
The order of precedence with using the + operator to merge these arrays is from left to right. So if we add $array1 and $array2 like so, 'apple' has precendence over 'banana' for the fruit element:
Doing this:
results in this:
And the other way around:
results in this:
0 comments:
Post a Comment