How to calculate compound interest in PHP

1 Answer

0 votes
function calculateCompoundInterest($principal, $rate, $years) {
    // Validate input: all values must be non-negative
    if ($principal < 0 || $rate < 0 || $years < 0) {
        echo "Error: Principal, rate, and years must be non-negative values.\n";
        return -1;
    }

    // Calculate total amount using the compound interest formula
    $amount = $principal * pow(1 + $rate / 100, $years);

    // Return compound interest (total amount - principal)
    return $amount - $principal;
}

$principal = 100000;
$rate = 3.5;
$years = 5;

$compoundInterest = calculateCompoundInterest($principal, $rate, $years);

if ($compoundInterest >= 0) {
    echo "Principal Amount: " . number_format($principal, 2) . "\n";
    echo "Annual Interest Rate: " . number_format($rate, 2) . "%\n";
    echo "Years: " . number_format($years, 2) . "\n";
    echo "Compound Interest: " . number_format($compoundInterest, 2) . "\n";
    echo "Total Amount: " . number_format($principal + $compoundInterest, 2) . "\n";
}




/*
run:
    
Principal Amount: 100,000.00
Annual Interest Rate: 3.50%
Years: 5.00
Compound Interest: 18,768.63
Total Amount: 118,768.63
    
*/

 



answered Aug 30, 2025 by avibootz

Related questions

...