Skip to content

Mortgage Calculator — PHP source

Compute monthly payments, the full amortization schedule and total interest, with extra-payment what-if analysis showing months and interest saved — runs entirely in your browser.

This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
/**
 * mortgage-calculator - amortized monthly payment.
 *
 * Display snippet: ports the core monthlyPayment() formula from the
 * TypeScript lib (src/lib/mortgage.ts). The full amortization schedule
 * (integer-cent tracking, extra payments, payoff dates) lives in the
 * TypeScript/Go sources.
 *
 * Standard amortization formula: P*r*(1+r)**n / ((1+r)**n - 1) with
 * r = $ratePct/100/12 and n = $years*12. A zero rate divides the
 * principal evenly. Returns the payment rounded to cents, or null on
 * invalid input. Standard library only.
 */

function monthlyPayment(float $principal, float $ratePct, int $years): ?float
{
    if (!is_finite($principal) || !is_finite($ratePct) || $principal <= 0 || $years <= 0) {
        return null;
    }

    $r = $ratePct / 100 / 12;
    $n = $years * 12;
    $payment = $r === 0.0
        ? $principal / $n
        : ($principal * $r * (1 + $r) ** $n) / ((1 + $r) ** $n - 1);
    return round($payment, 2);
}

// Example:
//   monthlyPayment(300000, 6, 30) -> 1798.65

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →