How can recursive functions be optimized for efficiency in PHP?
Recursive functions can be optimized for efficiency in PHP by implementing memoization. Memoization involves storing the results of expensive function calls and reusing them when the same inputs occur again. This can reduce redundant calculations and improve the overall performance of the recursive function.
<?php
function fibonacci($n, $memo = []) {
if (array_key_exists($n, $memo)) {
return $memo[$n];
}
if ($n <= 1) {
return $n;
}
$memo[$n] = fibonacci($n - 1, $memo) + fibonacci($n - 2, $memo);
return $memo[$n];
}
echo fibonacci(10);
?>