Back to questions
JuniorTheoryCommon
What does the program print?
<?php
function countdown(int $n): string
{
if ($n === 0) {
return 'go';
}
return $n . countdown($n - 1);
}
echo countdown(3), "\n";321go
- Expecting
123go, as if the deepest call came first: each call puts its own$nbefore the inner result, so the3of the outer call opens the string. - Expecting the base case to print first:
return 'go'hands its value back to the caller, and every call above it adds its own$nin front.
- What would
countdown(-1)do, and how would you guard against it? - How would you change line 8 so that the program prints
go123?