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];
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".
To elaborate a little on Joel's answer:
splice
modifies original collection and returns extracted elementsThen 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With