<?php
error_reporting(-1);

$credit = 40000;
$percent = 0.03;
$commission = 1000;
$payment = 5000;

$rate = 1 + $percent;

do {
    $credit = $credit * $rate + $commission;
    $log .= "Current month sum: $credit <br />";

    $credit -= $payment;
    $log .= "Sum, after anon paid: $credit <br />";

    $period++;
    $log .= "Current month $period<br />";

} while (($credit * $rate + $commission) > $payment);

$period++;
$log .= "Current month sum: $credit <br />";

$sum = $period * $payment + $credit;
$credit = 0;
$log .= "Sum, after anon paid: $credit <br /> Current month $period<br />";

echo "Anon paid for $period month. <br /> Whole sum: $sum.<br /> Credit: $credit";
echo '<hr />';
echo $log;