mercredi 9 janvier 2019

PHP function returns the wrong value. Tested with echo

I have a function where I calculate the return time of a given cashflow. Since yesterday it now returns the wrong value. I have tried putting an echo and exit in the function, where I get the right result, but the value returned is different.

Out of sheer desperation I even tried to unset the variable after returning.

$TBT = calcTBT($totalSavings); // $totalSavings is a array(15) with floats
echo $TBT; // shows 20, which in this case is wrong

function calcTBT($CF){
$length = count($CF);
$cumulCashFlow = array_fill(0, $length, 0);

$cumulCashFlow[0] = $CF[0];
for($y = 1; $y <= $length - 1; $y++){
    $cumulCashFlow[$y] = $cumulCashFlow[$y-1] + $CF[$y];
}

$tbt = 0;
for($y = 1; $y <= $length - 1; $y++){
    if($cumulCashFlow[$y] > 0 && $tbt === 0){
        $tbt = ($y - 1) + abs($cumulCashFlow[$y-1]/$CF[$y]);
    }
}

echo $tbt; //Shows in this case 9.74

if($tbt === 0){
    $tbt = 20;
}

return round($tbt, 2);
}

As shown in the code comments I expect a value of 9.74 and not 20. I even run the function again at an earlier time, where I get the expected result.

Aucun commentaire:

Enregistrer un commentaire