Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

go's avatar
Level 2

Collection merge - indexes are overwritten as #'s, not combined?

Hi,

I'm trying to merge two collections, one of one Model type, and another of another Model type, then sort them by the updated_at field.

$merged = $foo->merge($bar)->sortByDesc('updated_at');

It is overwriting indexes though, but they are number based, like:

Collection {#456 ▼
  #items: array:6 [▼
    0 => Foo {#463 ▶}
    1 => Foo {#464 ▶}
    5 => Foo {#468 ▶}
    4 => Bar {#376 ▶}
    3 => Bar {#394 ▶}
    2 => Bar {#395 ▶}
  ]
}

There should be 9 indexes in the example above.

According to the documentation, these should be appended when there is a number index? Is there an easy workaround to this, or another method to use?

Thanks

0 likes
3 replies
go's avatar
Level 2

Note, I just looped through the first collection and used prepend to add elements to the second collection, but if someone can confirm to me that this is intended functionality, I'll close this thread.

Seems like merge should add them together, as I have manually done, according to the docs.

Thanks

ejdelmonico's avatar

Have you looked at union or collapse? These two also deal with combining collections or arrays. The problem with merge si that if two keys are the same, only one will survive.

go's avatar
Level 2

I tried using collapse but unsuccessfully, because it seems to require arrays. I suppose you could flatten each collection into an array?

Please or to participate in this conversation.