Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple recursive function is not working

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.

like image 425
CJT3 Avatar asked Mar 31 '26 14:03

CJT3


2 Answers

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();
like image 120
Supericy Avatar answered Apr 03 '26 04:04

Supericy


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

like image 38
Sterling Archer Avatar answered Apr 03 '26 04:04

Sterling Archer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!