installment due by period - PHP

Viewed 144

the code snippet below shows a simulation of installments, with fixed expiration dates, divided every 30 days!

I would like to include a periodic expiration date, for example, every 20 days, or 10 every 10, depending on the variable $periodicity;

I have no idea how to do it?

<?php
function calculate_due($num_installment, $first_due_date = null){
  if($first_due_date != null)
  {
    $first_due_date = explode('/',$first_due_date);
    $day = $first_due_date[0];
    $month = $first_due_date[1];
    $year = $first_due_date[2];
  }
  else
  {
    $day = date('d');
    $month = date('m');
    $year = date('Y');
  }
  
  $periodicity = 20;
 
  for($installment = 0; $installment < $num_installment; $installment++)
  {
      if ($periodicity == 30)
          echo date('d/m/Y', strtotime('+'.$installment. " month", mktime(0, 0, 0, $month, $day, $year))),'<br/>';
      else
          echo date('d/m/Y', strtotime('+'.$installment. " month", mktime(0, 0, 0, $month, $periodicity, $year))),'<br/>';
  }
}
 

echo 'Calculates installments from an informed date<br/>';
calculate_due(5, '10/10/2020');
1 Answers

Try this,

<?php
function calculate_due($num_installment, $first_due_date = null, $days = 1){

    $start = DateTime::createFromFormat('d/m/Y', $first_due_date);
    
    $end = DateTime::createFromFormat('d/m/Y', $first_due_date);
    $end->add(new DateInterval('P'.($num_installment * $days).'D'));
    
    $period = new DatePeriod(
        $start,
        new DateInterval('P'.$days.'D'),
        $end
    );
    
    $return = [];
    foreach ($period as $date) {
       $return[] = $date->format('d/m/Y');    
    }
    return $return;
}
 
echo 'Calculates installments from an informed date<br/>'.PHP_EOL;

echo implode("\n", calculate_due(5, '10/10/2020', 20));

https://3v4l.org/TLR8a

Change 20 (the last function parameter) to suit the number of days between.

Result:

Calculates installments from an informed date<br/>
10/10/2020<br/>
30/10/2020<br/>
19/11/2020<br/>
09/12/2020<br/>
29/12/2020<br/>
Related