I’m writing a function for exploring an XML document, and need to use recursion. It’s not quite behaving how I wanted, so started running some tests.
<?php
$i=0;
function recursion(){
$i++;
if($i < 10){recursion();}
echo $i;
}
recursion();
?>
This generates a 500 Internal Server Error. Seems like I’m mishandling something – can someone help me out?
$iinside the function does not refer to the global variable$i, so it is always 1 and the script overflows the stack.You could make
$iglobal, but it’s much better to pass it as an argument: