PHP
Recursively Flatten a Multi-Dimensional Array
Convert any deeply nested PHP array into a single-dimensional array, collecting all scalar values for easier processing and iteration across complex data structures.
<?php
function flatten_array_recursive($array) {
$result = [];
foreach ($array as $value) {
if (is_array($value)) {
$result = array_merge($result, flatten_array_recursive($value));
} else {
$result[] = $value;
}
}
return $result;
}
$nested_array = [
1,
[2, 3],
[4, [5, 6, [7]]],
8
];
echo "Original nested array:
";
print_r($nested_array);
$flattened_array = flatten_array_recursive($nested_array);
echo "
Flattened array:
";
print_r($flattened_array);
$assoc_nested = [
'a' => 1,
'b' => ['x' => 2, 'y' => 3],
'c' => [
'd' => 4,
'e' => ['z' => 5]
]
];
echo "
Original associative nested array:
";
print_r($assoc_nested);
$flattened_assoc = flatten_array_recursive($assoc_nested);
echo "
Flattened associative array:
";
print_r($flattened_assoc);
?>
How it works: The `flatten_array_recursive` function processes a multi-dimensional array and returns a single, one-dimensional array containing all scalar values. It works by iterating through the input array. If an element is an array, it calls itself recursively on that element and merges the results. If an element is a scalar value, it's directly added to the result, ensuring all values from any depth are collected.