# Calculating compound interest

## Recommended Posts

Posted (edited)

I tried using a for loop but I'm trying to think of a way to calculate interest for a number of years but after I have the amount of interest for one year I'm unsure of how to add the interest to the principle then calculate it again for the next year, to hold that number like \$Principle + \$Interest = \$NewPrinciple then \$NewPrinciple + \$Interest for multiple years.

```<?php
if (isset(\$_POST['submit'])) {
\$InvestmentFrequency = \$_POST['InvestmentFrequency'];
\$CompoundFrequency = \$_POST['CompoundFrequency'];
\$InitialInvestment = preg_replace("/[^0-9]/", '', \$_POST['InitialInvestment']);
\$Contributions = preg_replace("/[^0-9]/", '', \$_POST['Contributions']);
\$InvestmentLength = preg_replace("/[^0-9]/", '', \$_POST['InvestmentLength']);
\$InterestRate =  \$_POST['InterestRate'];

if (\$InvestmentFrequency == "Weekly") {
\$InvestmentFrequency = "52";
} elseif (\$InvestmentFrequency == "Monthly") {
\$InvestmentFrequency = "12";
} else {
\$InvestmentFrequency = "1";
}

if (\$CompoundFrequency == "Annually") {
\$CompoundFrequency = "1";
} elseif (\$CompoundFrequency == "Semiannually") {
\$CompoundFrequency = "2";
} elseif (\$CompoundFrequency == "Monthly") {
\$CompoundFrequency = "12";
} elseif (\$CompoundFrequency == "Weekly") {
\$CompoundFrequency = "52";
} else {
\$CompoundFrequency = "365";
}

if (\$CompoundFrequency == "1") {
\$Interest = \$Principle * \$InterestRate;
\$NewPrinciple = \$Principle + \$Interest;

for (\$x = 0; \$x <= \$InvestmentLength; \$x++){
echo "\$x - \$NewPrinciple</br>";
}
}

}```

This is the output I get the principle and interest added together for the number of years I entered.

Edited by dataxspy

##### Share on other sites

What if I told you that you don't need a loop?

##### Share on other sites
Posted (edited)

Adapt the standard compound interest formula:

A=P(1+r/n)^(nt)

Where:

A= amount

P=principle

r= interest rate

n= number of compoundings per year

t= number of time periods

For continuous compounding use:

A=Pe^(rt)

Where:

t=time in years (can be a fraction)

e= mathematical constant (2.71828)

Edited by gw1500se

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×

×

• #### Activity

• Chat
×
• Create New...