How can recursion be implemented effectively when dealing with arrays in PHP?
When dealing with arrays in PHP, recursion can be implemented effectively by creating a function that calls itself to traverse nested arrays. This allows for processing of arrays with unknown depth or structure without the need for multiple nested loops.
function processArray($array) {
foreach ($array as $element) {
if (is_array($element)) {
processArray($element);
} else {
// Process individual elements here
echo $element . "\n";
}
}
}
// Example usage
$array = [1, 2, [3, 4, [5, 6]], 7];
processArray($array);