Q:

Php function with return statement

Can somebody explain me this code?  I don't understand why it outputs 21.
<?php
function math($t){

if($t==0)
return 0;    
return $t+ math($t-1);

}   
 echo math(6);

       ?>

It will echo 21. I have no idea how it got this result.

A:

The function is recursive, it calls itself until it gets to 0, then adds all the previously returned values (6,5,4,3,2,1).
function math($t){
    if($t==0)
        return 0;    
    return $t+ math($t-1);

}   
echo math(6);

So on loop one it gets 6 then 6-1 = 5 so math gets called again with  5 this time and so on. Take a look at http://sandbox.onlinephpfunctions.com/code/e228f3b696c5058efee03fa978a09179c1f2ffbb.

