echo and return print different values

Viewed 71

I am working on php bcmath extention for factorial calculation and i find that echo and return cause different result

This Code generate wrong result

<?php
    $a = 25;
    function test($a){
        if($a>1){
        $sum   =   bcmul($a, test($a-1)) ;
            echo $sum;
        } 
       if($a == 1) { return $a ;}
    }
    test($a);   // Output  200000000000000000000000
    ?>  

while below code generate correct result

<?php 
$a = 25;
function test($a){
    if($a>1){
    $sum   =   bcmul($a, test($a-1)) ;
        return $sum;
    } 
   if($a == 1) { return $a ;}
}
echo test($a);

?>

this problem generate 200000000000000000000000 result with echo $sum and return wrong result but if i echo test() and return $sum then it tend to right result 15511210043330985984000000. why

1 Answers

Please use the latter version with return and echo test() because you are using recursion (see the line with test($a-1)). Recursion only works correctly when using return statements which pass the interim results back to next higher level level in the stack.

echo on the other hand doesn't return the interim results to be calculated further - it just prints them out.

Related