Prev | Current Page 193 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

Specifically,
the following example uses recursion to create a payment schedule, telling you
the principal and interest amounts required of each payment installment to repay the
loan. The recursive function, amortizationTable(), is introduced in Listing 4-1. It takes as
input four arguments: $pNum, which identifies the payment number; $periodicPayment,
which carries the total monthly payment; $balance, which indicates the remaining loan
balance; and $monthlyInterest, which determines the monthly interest percentage
rate. These items are designated or determined in the script listed in Listing 4-2.
Listing 4-1. The Payment Calculator Function, amortizationTable()
function amortizationTable($pNum, $periodicPayment, $balance, $monthlyInterest)
{
// Calculate payment interest
$paymentInterest = round($balance * $monthlyInterest, 2);
// Calculate payment principal
$paymentPrincipal = round($periodicPayment - $paymentInterest, 2);
// Deduct principal from remaining balance
$newBalance = round($balance - $paymentPrincipal, 2);
122 CHAPTER 4 ?–  F UNCT I ONS
// If new balance < monthly payment, set to zero
if ($newBalance < $paymentPrincipal) {
$newBalance = 0;
}
printf("%d", $pNum);
printf("$%s", number_format($newBalance, 2));
printf("$%s", number_format($periodicPayment, 2));
printf("$%s", number_format($paymentPrincipal, 2));
printf("$%s", number_format($paymentInterest, 2));
# If balance not yet zero, recursively call amortizationTable()
if ($newBalance > 0) {
$pNum++;
amortizationTable($pNum, $periodicPayment,
$newBalance, $monthlyInterest);
} else {
return 0;
}
}
After setting pertinent variables and performing a few preliminary calculations,
Listing 4-2 invokes the amortizationTable() function.


Pages:
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205