PHP
Flatten Multi-Dimensional PHP Array Recursively
Learn to convert a nested, multi-dimensional PHP array into a single-dimensional flat array using a recursive function, simplifying data processing.
<?php
$nestedArray = [
'a' => 1,
'b' => [
'c' => 2,
'd' => [
'e' => 3,
'f' => 4,
],
],
'g' => 5,
'h' => ['i' => 6],
];
function flattenArray(array $array): array {
$result = [];
foreach ($array as $value) {
if (is_array($value)) {
$result = array_merge($result, flattenArray($value));
} else {
$result[] = $value;
}
}
return $result;
}
$flatArray = flattenArray($nestedArray);
echo "Original Nested Array:
";
print_r($nestedArray);
echo "
Flattened Array:
";
print_r($flatArray);
?>
How it works: This snippet provides a recursive function, flattenArray(), to convert any multi-dimensional PHP array into a single, one-dimensional array. It iterates through the input array; if an element is itself an array, it recursively calls flattenArray() on that element and merges the results. Otherwise, it directly adds the element to the result array.