Is using recursion a recommended method for handling nested arrays in PHP?
When dealing with nested arrays in PHP, using recursion is a recommended method as it allows you to easily traverse through the nested structure without having to know the depth of the array beforehand. Recursion simplifies the code and makes it more maintainable, especially when dealing with arrays of unknown depth.
function flattenArray($array) {
$result = [];
foreach ($array as $value) {
if (is_array($value)) {
$result = array_merge($result, flattenArray($value));
} else {
$result[] = $value;
}
}
return $result;
}
// Example usage
$nestedArray = [1, 2, [3, 4, [5, 6]], 7];
$flattenedArray = flattenArray($nestedArray);
print_r($flattenedArray);