Laravel Collection Public API: implode

November 29, 2016 —John Koster

implode($value, $glue = null)

The implode method will combine the items of the collection together. The Collection's implode method behaves differently than PHP's implode function in that it can operate on arrays of primitive data types as well as arrays of objects and arrays. Like PHP's implode function, the returned value is a string with the glue between each item.

The following code example demonstrates how to use the implode function to combine a simple array of primitive data types. When using implode in this context, the only parameter required is string that should be used to "glue" the items together:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'first', 'second', 'third'
8]);
9 
10// first-second-third
11$imploded = $collection->implode('-');

When using the implode method on collections that contain arrays or objects, two arguments are required: the $value that should be combined and the $glue that should combine each value. The following code example shows how to use the implode method in this context:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 ['name' => 'Laravel', 'version' => '5.1'],
8 ['name' => 'Lumen', 'version' => '5.0']
9]);
10 
11// Laravel, Lumen
12$imploded = $collection->implode('name', ', ');

The above code sample shows how to use the implode method with collections containing arrays. The following code sample will use Eloquent's model factory to create instances of the User class with some fake data. The final result of the code sample will be to create a message that can be displayed to end users of a micro-blogging platform that allows users to follow each other:

1<?php
2 
3// The make() method returns a collection instance.
4$users = factory('App\User', 3)->make();
5 
6$notification = $users->take(2)->implode('name', ', ') .
7 ' and '.$users->last()->name .
8 ' have recently followed you.';

The exact value of $notification will change each time the above code is executed because random data is being populated using the Faker package. However, the above script produces results similar to the following:

1Kathryn Fisher, Pink Spencer and Ben Pagac have recently followed you.
2Maureen Anderson, Samson Ondricka DVM and Otis Metz have recently followed you.
3Herman Ziemann, Shemar Tremblay and Presley Barrows have recently followed you.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.