Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Sep 8 Previous

Item 547189

Consider the following PHP program:

function beatsMe($a) { if ($a) { return beatsMe(substr($a,1)) . $a[0]; } }

print beatsMe("The time you enjoy wasting is not wasted time."); ?>


The quote used is one by Bertrand Russell but that's not the question. The question is what does the function beatsMe do.

A: The function calls itself, that's bad programming practice and is not allowed in PHP.
B: It returns the last letter of the string.
C: It returns the first letter of the string.
D: It returns a reversed version of the given string.
E: It chops off the first letter of the string, appends it to the end and then returns that value.


It is perfectly legal for functions to call themselves. It is called recursion and is used for all sorts of useful purposes such as creating pretty pictures.

Many people have a hard time understanding recursion and although answers B, C and E all have some validity the correct answer is D: the function returns a reversed string. How does it work? First get rid of that function name and replace it with a proper one:

function reverse($a) {
    if ($a) {
        return reverse(substr($a, 1)) . $a[0];

Not seeing it yet? Try to fill in "ABC" for $a:

function reverse("ABC") {
    if ("ABC") {
        return reverse("BC") . "A";

And "A" concatenated to the reverse of "BC" is "CBA", isn't it.

Recursion is not an exam subject but scope is, and recursive algorithms rely heavily on variable scope. In this example a new variable with the name $a is created in function scope each time reverse is called. All these $a variables cannot see or influence each other and they keep their value until the function call exits.

Here the values of the $a variables are respectively "ABC", "BC", "C" and "". Of all but the last the first letter is returned, thus effectively returning "C" + "B" + "A": the reversed string. The $a variable with the value "ABC" that was created in the first function call stays alive and intact until all inner calls to reverse have ended and then its first letter "A" is appended to the reverse of "BC".