Skip to content

Compound Interest Calculator — PHP source

Project investment growth with any compounding frequency, scheduled contributions and inflation adjustment. Yearly breakdown, growth curve and CSV export — runs entirely in your browser.

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

<?php
/**
 * compound-interest-calculator - compound growth projection.
 *
 * Display snippet: ports the core project() math from the TypeScript lib
 * (src/lib/interest.ts). The full projection (contributions, inflation,
 * per-year rows) lives in the TypeScript/Go sources.
 *
 * Semantics: monthly simulation with the monthly rate set to the exact
 * equivalent of the stated compounding frequency — (1 + r/n)**(n/12) - 1 —
 * so the effective annual rate is preserved for every supported
 * frequency. Returns the final balance rounded to 2 decimals, or null on
 * invalid input (negative principal, negative years, unsupported
 * frequency, non-finite values). Standard library only.
 */

const VALID_COMPOUNDS = [1, 2, 4, 12, 365];

function project(float $principal, float $ratePct, int $years, int $compoundsPerYear): ?float
{
    if (!is_finite($principal) || !is_finite($ratePct)) {
        return null;
    }
    if ($principal < 0 || $years < 0 || !in_array($compoundsPerYear, VALID_COMPOUNDS, true)) {
        return null;
    }

    $monthlyRate = (1 + $ratePct / 100 / $compoundsPerYear) ** ($compoundsPerYear / 12) - 1;

    $balance = $principal;
    for ($month = 0; $month < $years * 12; $month++) {
        $balance *= 1 + $monthlyRate;
    }
    return round($balance, 2);
}

// Example:
//   project(10000, 5, 10, 12) -> 16470.09

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 →