Search

Laravel Collection Public API: flatten

November 29, 2016 —John Koster

flatten

The flatten method will return a new Collection instance representing a flattened version of the original collection's items. The flatten method internally makes use of the Illuminate\Support\Arr::flatten($array) helper method. The flatten method will not preserve any keys from the original collection.

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'first',
8 'second' => [
9 'nested',
10 'array',
11 [
12 'deeply',
13 'nested'
14 ]
15 ],
16 'third' => 'some-value'
17]);
18 
19// Flatten the original collection.
20$flattenedCollection = $collection->flatten();

The $flattenedCollection variable will hold an instance of the Collection class and will have a value similar to the following output:

1object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=6)
4 0 => string 'first' (length=5)
5 1 => string 'nested' (length=6)
6 2 => string 'array' (length=5)
7 3 => string 'deeply' (length=6)
8 4 => string 'nested' (length=6)
9 5 => string 'some-value' (length=10)

It is obvious in the above output that the flatten method does not preserve any of the original keys, and will even flatten deeply nested arrays.