flatten() and collapse()

Flatten a multi-dimensional array into a single level.

Syntax\Illuminate\Support\Arr::flatten($array);

The Arr::flatten() method flattens a multi-dimensional array into a single level. Arr::collapse() merges an array of arrays into one array.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A tag cloud builder flattens a two-dimensional array of tags-per-category into a single list before counting unique values.
  • A search indexer flattens nested address arrays into a single level before passing them to an external API that expects flat key-value pairs.
  • A migration script collapses multiple levels of nested permission groups into a flat list so it can loop over every permission in one foreach.

More examples

Flatten a nested array

Arr::flatten() collapses any number of nesting levels into a single indexed array of scalar values.

Example · php
use Illuminate\Support\Arr;

$nested = ['php', ['laravel', 'symfony'], ['vue', 'react']];

$flat = Arr::flatten($nested);
// => ['php', 'laravel', 'symfony', 'vue', 'react']

Flatten only one level deep

Passing a depth argument to Arr::flatten() limits how many levels of nesting are collapsed, preserving deeper structures.

Example · php
use Illuminate\Support\Arr;

$data = [['a', 'b'], ['c', ['d', 'e']]];

$oneLevel = Arr::flatten($data, 1);
// => ['a', 'b', 'c', ['d', 'e']]
// The inner ['d','e'] is NOT unwrapped

Collapse values via Arr::collapse()

Arr::collapse() merges an array of arrays into a single array, with later values overwriting earlier ones for duplicate keys.

Example · php
use Illuminate\Support\Arr;

$chunks = [
    ['id' => 1, 'tag' => 'laravel'],
    ['id' => 2, 'tag' => 'php'],
    ['id' => 3, 'tag' => 'mysql'],
];

// Collapse a collection of arrays into one
$merged = Arr::collapse($chunks);
// => ['id' => 3, 'tag' => 'mysql']  (later keys overwrite earlier ones)

Discussion

  • Be the first to comment on this lesson.