Distribute a payment value through monthly period

Steps:

1) Get total months with ceil() function.

2) It will return 4 months. 3 months fully paid and one month paid only 50000.

3) Now, for each loop will add 10000 to total rent paid.

4) if this surpasses the amount paid, get mod which is 50000

$rent       = 100000; // rent amount
$amountPaid = 350000; // amount paid by tenant
$length     = ceil($amountPaid/$rent); // number of months paid for
$totalRent = 0;
for ($c = 1; $c <= $length; $c++) {
    $totalRent += $rent;
    $foreachMonth = $rent;
    if ($amountPaid < $totalRent) { // Here is the logic, if amount exceeds, use the remaining amount.
        $foreachMonth = $amountPaid % $rent;
    }    
    assignRentFunction($c, $foreachMonth);
}
function assignRentFunction($count, $amt) {
    echo "Month ".$count.': '.$amt."<br>";
}

**Output:**

Month 1: 100000
Month 2: 100000
Month 3: 100000
Month 4: 50000

Since there seems to be a few ways to slice this, I thought I'd throw my hat in the ring also:

for($c = 1; $c<=ceil($amountPaid/$rent); $c++){
    assignRentFunction($c, $rent - max(($c * $rent - $amountPaid),0));
}

And now the commented version:

for($month = 1; $month<=ceil($amountPaid/$rent); $month++){
    //For each month there is money for rent (using ceil() to account for fractions)

    assignRentFunction(
        $month,
        // The number of the month

        $rent
        //Show the rent ($rent)

        -
        //Deduct

        max(($month * $rent - $amountPaid),0)
        //Any difference if the whole rent for that month hasn't been paid

        /**
         * This relies on a little hack with the max() function:
         * max($var,0) will return 0 if $var is less than 0.
         * So we check to see if the sum of rent up to that month ($month * $rent)
         * is greater than what was paid ($month * $rent) - $amountPaid.
         * If it isn't because it's wrapped in the max,
         * the net (negative) number will just be shown as nill.
         * If it is, the net positive number will be subtracted
         * from the month's rent.
         **/
    );
}

$rent= 100000; // rent amount
$amountPaid= 350000; // amount paid by tenant
$length= $amountPaid/$rent; // number of months paid for
for ($c = 1; $c <= ceil($length); $c++) 
{
    $foreachMonth = 100000;
    if($amountPaid>$rent)
    {
        $rent=$rent;
        $amountPaid=$amountPaid-$rent;
    }
    else
    {
        $rent=$rent-$amountPaid;
    }
    assignRentFunction($c, $rent);
}

function assignRentFunction($count, $amt)
{

    echo "Month ".$count.': '.$amt."<br>";
}

Tags:

Php

Arrays