How to "flatten" a multi-dimensional array to simple one in PHP?
In PHP, you can use the "array_reduce" function to flatten a multi-dimensional array. This function takes two arguments: the array to be flattened and a callback function that defines how to combine the array elements. Here is an example of how to flatten a multi-dimensional array by array_reduce function:
<?php
function flattenArray($array)
{
return array_reduce(
$array,
function ($carry, $item) {
if (is_array($item)) {
return array_merge($carry, flattenArray($item));
} else {
$carry[] = $item;
return $carry;
}
},
[]
);
}
$multiDimensionalArray = [1, [2, 3], [4, [5, 6]]];
$flattenedArray = flattenArray($multiDimensionalArray);
print_r($flattenedArray);
This will output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
Watch a video course
Learn object oriented PHP
Alternatively, you can use call_user_func_array
and array_merge
recursively to flatten array
<?php
function flatten_array($array)
{
$flat = [];
foreach ($array as $value) {
if (is_array($value)) {
$flat = array_merge($flat, flatten_array($value));
} else {
$flat[] = $value;
}
}
return $flat;
}
$multiDimensionalArray = [1, [2, 3], [4, [5, 6]]];
$flattenedArray = flatten_array($multiDimensionalArray);
print_r($flattenedArray);
This will also output the same result as above.