Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo and return print different values

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

like image 949
jay suthar Avatar asked Sep 27 '26 05:09

jay suthar


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.

like image 186
vgar Avatar answered Sep 29 '26 19:09

vgar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!