Skip to content

Core\Arr::flattenDeep

Core\Arr::flattenDeep(array<mixed> $a): array<mixed>Core\Arr::flattenDeep(
    array<mixed> $a,
): array<mixed>

Takes every array nested inside an array, however deep they go, and gives you all their values as one flat array. It replaces the recursive walk you would otherwise write yourself.

A value that is not an array is kept where it was met, so the order you read is the order the values sit in. The keys are gone at every level, and the result is numbered from 0. Core\Arr::flatten is the member that removes one level only.

Good to know: storing an array inside itself stores a copy of it, so the nesting is always finite and this member always finishes.

Parameters

  • $aarray<mixed>An array nested to any depth.

Return value

Returns array<mixed>. A list of every value that is not an array, in order, renumbered from "0". Its type is mixed, because the depth depends on the data and not on the type.

Examples

Every level at once

<?nvs
// Shows how to make one flat list out of arrays nested inside each other.
array<mixed> $nested = ['a', ['b', ['c', ['d']]]];
// `Core\Arr::flattenDeep` removes every level of nesting. This prints
// ["a","b","c","d"].
echo Core\Json::encode(Core\Arr::flattenDeep($nested)), "\n";
// This prints 4.
echo Core\Arr::count(Core\Arr::flattenDeep($nested)), "\n";
Output
["a","b","c","d"]
4

Values that are not arrays

<?nvs
// Shows where a value that is not an array ends up, and how this member differs
// from `Core\Arr::flatten`.
array<mixed> $mixed = [1, [2, 3], [[4]], 5];
// A value that is not an array keeps its place in the order. This prints
// [1,2,3,4,5].
echo Core\Json::encode(Core\Arr::flattenDeep($mixed)), "\n";
array<array<array<int>>> $levels = [[[4]], [[5]]];
// `Core\Arr::flatten` removes one level, so its values are still arrays. This
// prints [[4],[5]].
echo Core\Json::encode(Core\Arr::flatten($levels)), "\n";
Output
[1,2,3,4,5]
[[4],[5]]

Every label of a menu

<?nvs
// Shows how to read every entry of a menu that has menus inside it.
array<mixed> $menu = ['Home', ['Shop', ['Shoes', 'Shirts']], ['Help']];
array<mixed> $labels = Core\Arr::flattenDeep($menu);
// Every label comes out, whatever level it sat at. This prints
// ["Home","Shop","Shoes","Shirts","Help"].
echo Core\Json::encode($labels), "\n";
// You can now count them. This prints 5.
echo Core\Arr::count($labels), "\n";
Output
["Home","Shop","Shoes","Shirts","Help"]
5