PHP
Flatten a Multi-dimensional Array
Learn to convert a nested or multi-dimensional PHP array into a single-dimensional flat array using a recursive function.
<?php
/**
* Recursively flattens a multi-dimensional array into a single-dimensional array.
*
* @param array $array The array to flatten.
* @return array The flattened array.
*/
function flattenArray(array $array): array
{
$result = [];
foreach ($array as $item) {
if (is_array($item)) {
$result = array_merge($result, flattenArray($item));
} else {
$result[] = $item;
}
}
return $result;
}
$nestedArray = [
1,
[2, 3],
[4, [5, 6]],
7,
[8, [9, [10]]]
];
echo "Original Nested Array:
";
print_r($nestedArray);
$flatArray = flattenArray($nestedArray);
echo "Flattened Array:
";
print_r($flatArray);
$complexArray = [
'a' => 1,
'b' => [
'c' => 2,
'd' => [
'e' => 3,
'f' => 4
]
],
'g' => 5
];
echo "Original Complex Array:
";
print_r($complexArray);
$flatComplexArray = flattenArray($complexArray);
echo "Flattened Complex Array:
";
print_r($flatComplexArray);
?>
How it works: This snippet provides a recursive function `flattenArray()` to convert a multi-dimensional array into a single-dimensional one. It iterates through the input array; if an element is an array itself, it recursively calls `flattenArray()` on that element and merges the results. Otherwise, it adds the non-array element directly to the result. This is extremely useful for processing data structures where nested arrays need to be reduced to a simpler, linear list.