Use splice() Method to Remove Items from Collection in Laravel

Published on August 11, 2020 48 sec read

Sometimes we need to remove a portion of a collection. The splice() method is very useful to do this. Today we’re going to see some examples of the splice method.

Table of Contents

  1. Basic Usage
  2. Set Length
  3. Replacement

Basic Usage

I’m going to write a simple use of the splice() method:

use Illuminate\Support\Collection;

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

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

The output of dd($spliced):

Illuminate\Support\Collection {#257 ▼
  #items: array:4 [▼
    0 => 6
    1 => 7
    2 => 8
    3 => 9
  ]
}

And the dd($collection) contains the first 6 items.

Illuminate\Support\Collection {#263 ▼
  #items: array:6 [▼
    0 => 0
    1 => 1
    2 => 2
    3 => 3
    4 => 4
    5 => 5
  ]
}

Set Length

We can set legth to controll how long the section that is removed from the collection can be. Let’s splice from 3rd item and take next 4 items:

use Illuminate\Support\Collection;

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

$spliced = $collection->splice(3, 4);

The output of dd($spliced):

Illuminate\Support\Collection {#257 ▼
  #items: array:4 [▼
    0 => 3
    1 => 4
    2 => 5
    3 => 6
  ]
}

Like previous example, the $collection variable will now have the remaining items:

Illuminate\Support\Collection {#263 ▼
  #items: array:6 [▼
    0 => 0
    1 => 1
    2 => 2
    3 => 7
    4 => 8
    5 => 9
  ]
}

Replacement

Uisng splice method, we’re able to replace collection items.

use Illuminate\Support\Collection;

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

$spliced = $collection->splice(1, 3, [
    'Dhaka', 'London', 'Sydney'
]);

The output of dd($spliced):

Illuminate\Support\Collection {#257 ▼
  #items: array:3 [▼
    0 => "Berlin"
    1 => "Tokyo"
    2 => "Paris"
  ]
}

The output of dd($collection):

Illuminate\Support\Collection {#263 ▼
  #items: array:4 [▼
    0 => "Dublin"
    1 => "Dhaka"
    2 => "London"
    3 => "Sydney"
  ]
}

In this example, we’ve replaced Berlin, Tokyo, Paris with Dhaka, London, Sydney.

That’s it. Thanks for reading. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *