I’m trying to run a recursive function, but it doesn’t work properly. I don’t see any errors in my code, so maybe this is just not possible with PHP?
<?php
$herpNum = 0;
function herp() {
if ($herpNum == 22) {
echo "done";
} else {
$herpNum = $herpNum+1;
echo $herpNum."<br/>";
herp();
}
}
herp();
?>
when I run this, the result is just a long list of 1.
Because $herpNum isn’t in the same scope as the function, so it’s creating a new $herpNum inside the function which defaults to 0 and then is adding 1 to it.
You could either pass it in as an arguement or have it as a global variable.
or