Arr::collapse

Merges an array of arrays or collections one level down into a single flat array.

Signature
public static function collapse($array)
  • Added in Laravel 5.0

Parameters

ParameterTypeDescription
$$arrayiterableAn iterable whose elements are arrays or Illuminate collections. Elements of any other type are skipped.

Return value

arrayA single array containing the merged contents of each array or collection element.

Arr::collapse takes an array whose elements are themselves arrays and merges them into one array. It is deliberately shallow: it flattens exactly one level and stops. If you want everything reduced to a single list no matter how deep it goes, that is Arr::flatten.

When to reach for it

Reach for it whenever you hold grouped results and want them ungrouped — pages of records from a paginated API, per-role permission arrays, error bags collected per field, chunked jobs whose results you want as one list. Each element may be a plain array or an Illuminate\Support\Collection; collections are converted with all() before the merge.

What trips people up

Two things. First, elements that are neither arrays nor collections are dropped silently rather than appended, so [[1, 2], 3] collapses to [1, 2] with no warning and no error. Second, the merge is array_merge, which renumbers integer keys from zero and lets the last array win for duplicate string keys. If you are collapsing keyed rows and need the keys to survive, collapse first and re-key afterwards with Arr::keyBy.

Example

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

When to use it

  • Merging the per-page results of a paginated API response into one list.
  • Turning per-role permission arrays into a single flat permission set.
  • Combining several groups of validation messages into one array before display.

Frequently asked questions

What is the difference between Arr::collapse and Arr::flatten?

Collapse removes exactly one level of nesting, while flatten recurses all the way down by default. Collapse also keeps string keys from the inner arrays; flatten discards every key.

Why did Arr::collapse drop some of my values?

Elements that are not arrays or Collection instances are skipped silently, so a scalar sitting alongside your arrays disappears. Wrap such values in an array first if you need them in the result.

Does Arr::collapse preserve keys?

String keys from the inner arrays are preserved, with later arrays overwriting earlier ones, but integer keys are renumbered from zero because the merge uses array_merge.

More examples

Ungrouping permissions

Prints ["posts.create","posts.update","posts.view"]. Collapse discards the role keys and concatenates the inner lists, so duplicates survive the merge; array_unique removes them and sort makes the output stable regardless of the order the roles were declared in.

Example · php
<?php

use Illuminate\Support\Arr;

$byRole = [
    'editor' => ['posts.view', 'posts.update'],
    'author' => ['posts.view', 'posts.create'],
];

$all = array_values(array_unique(Arr::collapse($byRole)));
sort($all);

echo json_encode($all), "\n";

Collapse versus flatten

Prints [1,[2,3],4,[5]] then [1,2,3,4,5]. Collapse removes exactly one level and leaves the inner arrays as values; flatten keeps recursing until nothing but scalars remain. Choose collapse when the second level is data you want to keep intact.

Example · php
<?php

use Illuminate\Support\Arr;

$nested = [[1, [2, 3]], [4, [5]]];

echo json_encode(Arr::collapse($nested)), "\n";
echo json_encode(Arr::flatten($nested)), "\n";

Merging paginated pages in an application

Each element of $pages is the data array of one response, so collapse yields a single list of orders and count reports the total. This snippet needs a booted application because it uses the Http facade; the collapse call itself works anywhere.

Example · php
<?php

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;

$pages = [];

foreach (range(1, 3) as $page) {
    $pages[] = Http::get('https://api.example.com/orders', ['page' => $page])
        ->json('data');
}

$orders = Arr::collapse($pages);

echo count($orders), "\n";

Discussion

  • Be the first to comment on this lesson.