How to Deep Flatten and Multi-Dimensional Array in PHP with this function
title | tags |
---|---|
deepFlatten
|
array,recursion,intermediate
|
Deep flattens an array.
- Use recursion.
- Use
array_push
, splat operator and an empty array to flatten the array. - Recursively flatten each element that is an array.
function deepFlatten($items)
{
$result = [];
foreach ($items as $item) {
if (!is_array($item)) {
$result[] = $item;
} else {
array_push($result, ...deepFlatten($item));
}
}
return $result;
}
deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]