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

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

Laravel 5

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

public function implode(
    $value,
    $glue = null
);

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:

use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([
    'first', 'second', 'third'
]);

// first-second-third
$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:

use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([
    ['name' => 'Laravel', 'version' => '5.1'],
    ['name' => 'Lumen', 'version' => '5.0']
]);

// Laravel, Lumen
$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:

// The make() method returns a collection instance.
$users = factory('App\User', 3)->make();

$notification = $users->take(2)->implode('name', ', ') .
                ' and '.$users->last()->name . 
                ' 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:

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

Start the Discussion

Leave a comment

Subscribe to our newsletter