How to implement recursion in PHP?
Hello everyone! Please tell me how to properly implement recursion in PHP. I'm writing a function to traverse a multidimensional array and count all values, but I'm getting either 0 or an infinite loop.
Here's what I tried:
function recursiveSum($arr) {\n static $sum = 0;\n foreach ($arr as $value) {\n if (is_array($value)) {\n recursiveSum($value);\n } else {\n $sum += $value;\n }\n }\n return $sum;\n}\n\n$data = [1, [2, 3], [4, [5, 6]]];\necho recursiveSum($data); // expected: 21The problem is that when calling the function repeatedly with different arrays, the result accumulates due to the static variable. I also tried passing the sum by reference (&$sum), but then the function returns unexpected values. Also
No answers yet.
Log in to leave an answer