DEV Community

Morcos Gad
Morcos Gad

Posted on

Using splice() Method to Remove Items - Laravel

Found this great resource https://www.larashout.com/laravel-collection-using-splice-method-to-remove-items that shows us how to use splice() and use it in your next projects I will show briefly, but visit the source to go deeper.

The below example shows a very simple use of the splice() method

use Illuminate\Support\Collection;

$collection = new Collection([
    0,1,2,3,4,5,6,7,8,9
]);

// Splice the $collection from 5th index, which is 4
$spliced = $collection->splice(5);

dd($spliced); //return a new collection of remaining items like below.
/*
Illuminate\Support\Collection^ {#1338
  #items: array:5 [
    0 => 5
    1 => 6
    2 => 7
    3 => 8
    4 => 9
  ]
}
*/

dd($collection); //it will hold only the first five values of the original collection
/*
Illuminate\Support\Collection^ {#1341
  #items: array:5 [
    0 => 0
    1 => 1
    2 => 2
    3 => 3
    4 => 4
  ]
}
*/
Enter fullscreen mode Exit fullscreen mode

The $length parameter can be used to control how long the section that is removed from the collection can be. The following example shows, how you can remove three items from the collection

use Illuminate\Support\Collection;

$collection = new Collection([
    0,1,2,3,4,5,6,7,8,9
]);

// Splice the collection starting from 2nd item
// and take at most 3 items
$spliced = $collection->splice(2,3);

dd($spliced);
/*
Illuminate\Support\Collection {#656 ▼
  #items: array:3 [▼
    0 => 2
    1 => 3
    2 => 4
  ]
}
*/

dd($collection); //will now have the remaining items
/*
Illuminate\Support\Collection {#670 ▼
  #items: array:7 [▼
    0 => 0
    1 => 1
    2 => 5
    3 => 6
    4 => 7
    5 => 8
    6 => 9
  ]
}
*/
Enter fullscreen mode Exit fullscreen mode

The below example shows how you can use the $replacement parameter

use Illuminate\Support\Collection;

$collection = new Collection([
    'London', 'Paris', 'Dublin', 'Berlin'
]);

$spliced = $collection->splice(1, 3, [
    'New York', 'Tokyo', 'Sydney'
]);

dd($spliced);
/*
Illuminate\Support\Collection {#656 ▼
  #items: array:3 [▼
    0 => "Paris"
    1 => "Dublin"
    2 => "Berlin"
  ]
}
*/

dd($collection);
/*
Illuminate\Support\Collection {#670 ▼
  #items: array:4 [▼
    0 => "London"
    1 => "New York"
    2 => "Tokyo"
    3 => "Sydney"
  ]
}
*/
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed it as much as I did with this great code and information.

Top comments (0)