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.
$herpNum = 0;
function herp($herpNum) {
if ($herpNum == 22) {
echo "done";
} else {
$herpNum = $herpNum+1;
echo $herpNum."<br/>";
herp($herpNum);
}
}
herp($herpNum);
or
$herpNum = 0;
function herp() {
global $herpNum;
if ($herpNum == 22) {
echo "done";
} else {
$herpNum = $herpNum+1;
echo $herpNum."<br/>";
herp();
}
}
herp();
It's because you're not passing in the parameter $herpnum into the function.
<?php
$herpNum = 0;
function herp($herpNum) {
if ($herpNum == 22) {
echo "done";
} else {
$herpNum = $herpNum+1;
echo $herpNum."<br/>";
herp($herpNum);
}
}
herp($herpNum);
?>
That should work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With