为什么这个递归函数会像这样工作?

I am trying to learn recursion and have written a function that takes a number and count it down to zero and then count it up to the original number again, the function works, but what I don't understand is why it works as it does. I understnad why the first print after the else statement prints: "5 4 3 2 1" and then the number is 0 and the if statement prints: "0". It is after this scenario I don't understand since now the function enters the second print after the else statement and prints: "1 2 3 4 5" which is very strange to me. I would really appreciate if someone could explain this to me.

<?php
function rec_downandup($num){
    if($num == 0){
        print '0 ';
    }else{
        print $num.' ';
        rec_downandup($num-1);
        print $num.' ';
    }
}
rec_downandup(5);
?>

Output

5 4 3 2 1 0 1 2 3 4 5

When you take a closer look, it should become clear.

print $num.' ';
rec_downandup($num-1);
print $num.' ';

For your first input, you will get

print 5.' ';
rec_downandup(4);
print 5.' ';

and after that call it is

print 5.' ';
print 4.' ';
rec_downandup(3);
print 4.' ';
print 5.' ';

So it appears the functions counts down and up, but actually it just counts down and places each number twice - the second time in reverse order so it appears to be counting up.

The answer provided by @kingero is spot on, it explains exactly what is happening. If you want to have a straight countdown you would do this -

function rec_downandup($num){
    if($num == 0){
        print '0 ';
    }else{
        echo $num;
        $num = rec_downandup($num-1); // you can do this without the variable assignment, it just seems neater this way.
    }
}
rec_downandup(5);

Each time the re_downandup() function is called, the parameter $num takes the value passed to the function and it will keep that value until the function ends in its last closing brace.

Also important to understand is that in presence of a recursive call to the function, the execution flow continues in this call, this is why the second print won't happen until the execution returns from said recursive call.

So lets take this:

print $num.' ';
rec_downandup($num-1);
print $num.' ';

The first print $num will print the number, then the execution flow will continue in the new call to the function, which will show the variable's value minus one. This will continue to occur recursively until $num reaches zero.

When the recursion breaking condition $num == 0 is given, the function will "be allowed" to continue until the end; so each recursive call will return, and that is when the second print $num will begin to execute, for that is what happens when the execution flow of your program returns from rec_downandup().

The value printed in this case will be whatever value the $num variable had when the recursive call was triggered.