Use splice() Method to Remove Items from Collection in Laravel
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
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. ?Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.