3

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

jay suthar
  • 79
  • 7
  • 1
    `return` ends the function, `echo` doesn't? – Jeto Jan 15 '19 at 08:04
  • actually it's not about the difference between echo and return, it's just because you are using recursion into your function so you have to return the intermediate results – Frankich Jan 15 '19 at 08:38

1 Answers1

1

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.

vgar
  • 171
  • 6