Search

Laravel 5 Collections: Combining Collection Elements Into a String With implode

April 22, 2018 —John Koster

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.

#Signature

1public function implode(
2 $value,
3 $glue = null
4);

#Example Use

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:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', 'third'
6]);
7 
8// first-second-third
9$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:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 ['name' => 'Laravel', 'version' => '5.1'],
6 ['name' => 'Lumen', 'version' => '5.0']
7]);
8 
9// Laravel, Lumen
10$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// The make() method returns a collection instance.
2$users = factory('App\User', 3)->make();
3 
4$notification = $users->take(2)->implode('name', ', ') .
5 ' and '.$users->last()->name .
6 ' 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
2 Ben Pagac have recently followed you.
3Maureen Anderson, Samson Ondricka DVM and
4 Otis Metz have recently followed you.
5Herman Ziemann, Shemar Tremblay and
6 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.