I need help converting the following excel formula to PHP
PV(.0588/12,300,868.0583333)
The output I am expecting is 136,275.88
, but the output that I am getting is 590573.166
. I have spent hours on it but I can’t seem to find the solution.
This is my code
function FV($rate = 0, $nper = 0, $pmt = 0, $pv =0, $type = 0) { // Validate parameters if ($type != 0 && $type != 1) { return False; } // Calculate if ($rate != 0.0) { return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate; } else { return -$pv - $pmt * $nper; } } // function FV() echo FV(.0588/12, 300, -868.06);
I have gone through the similar post before but that does not solve.
I have also gone through the PHP site but that does not help either.
Advertisement
Answer
Your algorithm is for FV
, but apparently you want it for PV
. You’re in luck as Alejandro Pedraza already made a PEAR package Math_Finance
for this. Here’s the function extracted to prove that it works (you should include the full Finance.php
with its copyright info in your project!).
<?php /** * Extracted from the PEAR package Math_Finance by Alejandro Pedraza * http://pear.php.net/package/Math_Finance * * Returns the Present Value of a cash flow with constant payments and interest rate (annuities) * Excel equivalent: PV * * TVM functions solve for a term in the following formula: * pv(1+r)^n + pmt(1+r.type)((1+r)^n - 1)/r) +fv = 0 * * * @param float Interest rate per period * @param int Number of periods * @param float Periodic payment (annuity) * @param float Future Value * @param int Payment type: FINANCE_PAY_END (default): at the end of each period FINANCE_PAY_BEGIN: at the beginning of each period * @return float * @static * @access public */ function presentValue($rate, $nper, $pmt, $fv = 0, $type = 0) { if ($nper < 0) { return PEAR::raiseError('Number of periods must be positive'); } if ($type != FINANCE_PAY_END && $type != FINANCE_PAY_BEGIN) { return PEAR::raiseError('Payment type must be FINANCE_PAY_END or FINANCE_PAY_BEGIN'); } if ($rate) { $pv = (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper); } else { $pv = -$fv - $pmt * $nper; } return $pv; } ?>
Usage:
<?php var_dump( presentValue(.0588/12,300,868.0583333) ); // float(-136275.88429118) ?>
Note:
Like previously mentioned, you should use the full Finance.php
file from the PEAR page in order for this to work perfectly (as you might get notices of undefined constants, and it can’t raise errors). You can find the package HERE.