It does exactly as you tell it to.
function counterFunction(int $counter) :int
{
if ($counter < 3) {
$counter++; // mutate $counter to be increase by 1
echo "counter in recursive loop: ".$counter."</br>"; // print info with new $counter binding
counterFunction($counter); // call counterFunction AND DISCARD the result (it is not assigned or returned)
}
// This happens for each call regardless if it does recursion or not
echo "end condition reached.</br>"; // print info
echo "End Counter: ".$counter."</br>"; // print End counter for every stage or recursion, which is argument increased if argument was below 3
return $counter; // return argument increased by 1 regardless of possible recursion
}
You may think that two calls of counterFunction
shares $counter
, but they don't. They have their own copies of the argument unless it is an object or passed by reference. In this case it isn't.
To mend it you should use the result from the recursion. Eg.
function counterFunction(int $counter) :int
{
if ($counter < 3) {
echo "counter in recursive loop: {$counter}</br>"; // print info with current $counter binding (argument)
return counterFunction($counter+1); // call counterFunction with $counter+1 as argument and returne the result
}
// only happens when $counter >= 3. returns argument
echo "end condition reached.</br>"; // print info
echo "End Counter: {$counter}</br>"; // print End counter, which is the same as argument
return $counter; // return argument
}
Or you can update your counter with the result:
function counterFunction(int $counter) :int
{
if ($counter < 3) {
echo "counter in recursive loop: {$counter}</br>"; // print info with current $counter binding (argument)
$counter = counterFunction($counter+1); // call counterFunction with $counter+1 as argument and update $counter
}
// This happens for each call regardless if it does recursion or not
echo "end condition reached.</br>"; // print info
echo "End Counter: {$counter}</br>"; // print End counter, which is the same as argument
return $counter; // return argument
}
This has the possibly unwanted effect that you'll have several printings with "end condition" than the actual base case since every call with do it.