So next up let's talk about the recursion.
And for that we're gonna calculate the factorial.
Now every function that's recursive needs to have a base case.
That's a condition that basically stops the recursion.
And that's the simplest instance of the problem that can be solved directly.
This is how this can be technically described.
And in the case of factorial, when you calculate factorial of zero or factorial of one, the result
is always one.
So this basically returns from the function.
But then since the function is recursive, there needs to be a recursive case.
That's the case when the function calls itself.
And in case of factorial, everything above one is calling itself, but with an argument minus one.
So this is how factorial works.
Was this is a recursive function.
So for example, if we call factorial with the argument five.
Then you can see that clearly five is not zero or it isn't one.
So it will multiply five by factorial of four, and so on and so on up until the factorial will receive
either 1 or 0 as an argument.
Then the final result will be returned.
So in this case this is 120.
So let's do an actual example.
Let's run this code.
Let me create a recursive PHP file.
And let's type this code.
So we need a starting tag.
And we need the function called factorial which accepts n as a parameter.
Let's also type that and it also returns an int.
So we start with a base case.
So base case is n is either zero or n is one.
So that's our base case.
That's the case that would let this function return.
That will stop the recursion.
Now there also needs to be a recursive case when we actually call factorial within factorial.
So we're gonna multiply n by.
Sorry that's not a variable by factorial.
Passing n minus one.
Let's reformat this now so we can actually see what argument was called and when.
Let's echo.
N and add a new line.
Finally let's um let's run this function using var dump.
Let's call factorial passing five.
And what I expect is I expect to see every single time this function is being called.
And with what argument.
So we are running the recursive PHP file.
So the first call is with the argument five.
So we know that five is not 0 or 1.
So this is causing the recursion.
It's calling factorial again with four.
So obviously four is also none of this.
So it calls factorial with three.
And then there is another nested call with two.
And finally when factorial is called with one it returns one.
So it doesn't call factorial again.
It breaks the recursion so that all those nested factorial calls can also return the actual value,
because now the actual value, the the row number is known.
So then all of those nested factorial functions return up until the main factorial call, which can
also return a value to the caller, which is this line, and this returns this value.