Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to flatten a nested array

Short answer

For one level of nesting array_merge() with the spread operator is enough:

<?php
 
$nested = [[1, 2], [3], [4, 5]];
 
echo implode(', ', array_merge(...$nested));

Output:

1, 2, 3, 4, 5

Any depth

array_walk_recursive() visits the elements at every level:

<?php
 
$nested = [1, [2, [3, [4]]], 5];
$flat = [];
 
array_walk_recursive($nested, function ($value) use (&$flat) {
    $flat[] = $value;
});
 
echo implode(', ', $flat);

Output:

1, 2, 3, 4, 5

Functions used in this recipe

  • array_merge — Merges one or more arrays into one.
  • array_walk — Calls a function for every element of an array.

Thanks for reading!

Donate to the site — we work hard for you.