Calculating Monthly Loan Repayments in PHP

Daniel West
2 min readOct 6, 2017

--

If you’ve looked into this, you’ll probably know how much of a mine-field loan repayment calculations are.

In this article, I’ll share my solution for calculating monthly loan repayments, with annual compound interest and figures that match those that finance providers such as V12 provide.

I first found a calculator with more advanced options so I knew what the finance provider was using for their monthly repayment calculations, this one is REALLY good:

The first bit of very useful information I found was a formula to calculate the interest rate per period. It is not as simple as dividing the APR by 12!! I found the formula here:

Converted to PHP:

$apr = 0.159; // 15.9% APR
$totalPaymentsPerYear = 12;
$compoundPerYear = 1;
$interest = pow((1 + $apr/$compoundPerYear), $compoundPerYear/$totalPaymentsPerYear)-1;

With that I was on the hunt for how to use this information. I’m no expert in this field and found many calculations before the one above, and after. I somehow got lucky and stumbled across this page:

If you ever read this, Tony Marston — THANK YOU!

The article is old and he converted his scripts from an even older program he made in COBOL.

In there was the key, the calc_payment function. Well commented code shows the original formula. The function becomes:

function calcPayment(
float $loanAmount,
int $totalPayments,
float $interest
)
{
//***********************************************************
// INTEREST * ((1 + INTEREST) ^ TOTALPAYMENTS)
// PMT = LOAN * -------------------------------------------
// ((1 + INTEREST) ^ TOTALPAYMENTS) - 1
//***********************************************************

$value1 = $interest * pow((1 + $interest), $totalPayments);
$value2 = pow((1 + $interest), $totalPayments) - 1;
$pmt = $loanAmount * ($value1 / $value2);
return $pmt;
}

That’s it! Feed the monthly interest rate in and it will throw you back the monthly re-payments.

If you’re after a full payment schedule, read through Tony’s scripts.

This took me so long to find and figure out — I hope it saves someone else hours of time and effort bringing these bits of info together.

Happy coding!

--

--

Responses (1)