PHP Program to Find Compound Interest
Last Updated :
27 Feb, 2024
Compound interest is a financial concept that calculates the interest on the initial principal and also on the accumulated interest of previous periods. It is widely used in the banking, finance, and investment sectors. In this article, we will explore different approaches to calculating compound interest using PHP.
The formula for calculating compound interest is:
A = P (1 + \frac{r}{n})^{nt}
Where
- A is the amount after t years.
- P is the principal amount (initial investment).
- r is the annual interest rate (in decimal).
- n is the number of times interest is compounded per year.
- t is the number of years.
The basic method is to calculate compound interest in PHP is by directly using the formula. In this example, the compoundInterest()
function takes the principal amount, annual interest rate, time in years, and the compounding frequency as arguments. It returns the compound interest calculated using the formula.
PHP
<?php
function compoundInterest( $principal , $r , $t , $n ) {
$amount = $principal * pow((1 + $r / $n ), $n * $t );
$compoundInterest = $amount - $principal ;
return $compoundInterest ;
}
$P = 10000;
$r = 0.05;
$t = 5;
$n = 12;
echo number_format(compoundInterest( $P , $r , $t , $n ), 2);
?>
|
Compound Interest using a Loop
Another approach is to use a loop to calculate the compound interest. This method is useful when you need to track the interest accrued each compounding period. In this approach, the compoundInterest()
function iterates over the total number of compounding periods and accumulates the interest in each period. This method can be more flexible when dealing with complex compounding scenarios.
PHP
<?php
function compoundInterest( $principal , $r , $t , $n ) {
$amount = $principal ;
$compoundPeriod = $t * $n ;
for ( $i = 0; $i < $compoundPeriod ; $i ++) {
$amount += ( $amount * $r ) / $n ;
}
$compoundInterest = $amount - $principal ;
return $compoundInterest ;
}
$P = 10000;
$r = 0.05;
$t = 5;
$n = 12;
echo number_format(compoundInterest( $P , $r , $t , $n ), 2);
?>
|
Share your thoughts in the comments
Please Login to comment...