function factorial ($n) {

if ($n==0) return 1;

return factorial ($n - 1) * $n;

}

This is messing with my brain. It's a function to come up with the factorial of a given number (5 = 1*2*3*4*5). And it works. But I can't understand why.

Say $n = 4

it will try to return [factorial (3) * 4], but what is factorial (3)? How can it know that without knowing what the sublayers are?

If you go all the way down to factorial (1-1) you get a value of 1 returned. And 1 * 4 = 4 so it would return 4. So the next layer up we have

factorial(4-1) which is the same as factorial (3) which requires another loop. I'm so lost my head is spinning!!! Am I looking at this completely wrong?