Dangerous += operator on array

I saw two pull requests today that both did something like this:


foreach($array as $item) {
  $result += $this->someMethodThatReturnsArray();

This will not give the expected results, see for yourself: https://3v4l.org/66S6m

There are several solutions for this:

  • Use array_merge:
    $result = array_merge($result, $this->someMethodThatReturnsArray());
  • Use the array-spread operator:
    $result = [...$result, ...$this->someMethodThatReturnsArray()]
    (as of PHP 7.4. We are all using this, right? 7.3 is end of line, just mentioning)

Caveat: All this will create a lot of copies of the array, and there are ways to avoid most of them. But all the ways I can think on top of my head have costs in terms of readability. So, if you think you have an issue with performance, then first measure, then profile, and then – if you see that this is the actual source of your performance loss – only then optimize this.

About the author

People Enabler at CHECK24