5

I tried the following but it doesn't work.

$index = 2;
$collection->put($index, $item4);

For example if $collection looks like this:

$collection = [$item1, $item2, $item3];

I'd like to end up with:

$collection = [$item1, $item2, $item4, $item3];
Howard
  • 3,648
  • 13
  • 58
  • 86

2 Answers2

18

The easiest way would probably be to splice it in, like this:

$collection->splice(2, 0, [$item4]);

Collections usually support the same functionality as regular PHP arrays. In this case, it's the array_splice() function that's used behind the scenes.

By setting the second parameter to 0, you essentially tell PHP to "go to index 2 in the array, then remove 0 elements, then insert this element I just provided you with".

Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
  • I'm getting an error. Non-static method Illuminate\Support\Collection::splice() should not be called statically, assuming $this from incompatible context – Howard Jan 01 '15 at 17:49
  • Oops, my bad - should be ``->``, not ``::``. I'll update my example. – Joel Hinz Jan 01 '15 at 18:07
  • Tried that too. I'm getting. array_splice() expects parameter 2 to be long, object given – Howard Jan 01 '15 at 18:09
  • I'm sorry. I'm really tired after new year's... I messed up the argument order. Please look again, _should_ work now. If that doesn't work put $item4 in an array. – Joel Hinz Jan 01 '15 at 18:11
  • No worries. Sorry, I'm getting. Trying to get property of non-object. When I try using push or prepend it works though, FYI. If that helps any. – Howard Jan 01 '15 at 18:15
  • Great! :) Glad to hear it. – Joel Hinz Jan 01 '15 at 18:33
  • `splice` modifies original collection and returns extracted elements, so it actually should be `$collection->splice(2, 0, [$item4]);`, when new item is an object it should be wrapped in array. – Paul Jul 21 '16 at 15:31
  • 1
    took me a great deal of time to realize splice() modifies the collection itself instead of returning a new one as avalue. Do you know of any way to "splice" it and return the new collection? – Hop hop Nov 26 '16 at 15:58
3

To elaborate a little on Joel's answer:

  • splice modifies original collection and returns extracted elements
  • new item is typecasted to array, if that is not what we want we should wrap it in array

Then to add $item at index $index:

$collection->splice($index, 0, [$item]);

or generally:

$elements = $collection->splice($index, $number, [$item1, $item2, ...]);

where $number is number of elements we want to extract (and remove) from original collection.

Paul
  • 3,186
  • 1
  • 19
  • 22
  • "new item is typecasted to array, if that is not what we want we should wrap it in array," I experienced object to array casting and was scratching my head, thanks for this note. – AVProgrammer Jul 10 '19 at 00:16