Repeat a number of times in a range of days

0

I have this code that repeats a number of times the day of each week.

$hoje = new DateTime();
$semana = new DateInterval('P7D');
$repeticoes = 3;

// Printa primeira data antes de somar os dias
echo  $hoje->format('Y-m-d '.$_POST['hora_inicio'].":00".'') . "\n<br>";
echo  $hoje->format('Y-m-d '.$_POST['hora_final'].":00".'') . "\n<br><br>";



// Como já foi printada a primeira data, repete N-1 vezes
for ($i = 0 ; $i < $repeticoes - 1 ; $i++) {
    // Adiciona uma semana
    $hoje = $hoje->add($semana);
    // Printa data adicionada
echo $hoje->format('Y-m-d '.$_POST['hora_inicio'].":00".'') . "\n<br>";
echo  $hoje->format('Y-m-d '.$_POST['hora_final'].":00".'') . "\n<br><br>";          
 }

Code output above

2018-11-09

2018-11-16

2018-11-23

My debt would be as follows:

How can I repeat the interval between days by setting a deadline?

Example:

Today's date: 09/11/2018

Number of times to repeat between days: 3

Ending date: 16/11/2018

I need you to print:

09/11/2018

12/11/2018

15/11/2018

    
asked by anonymous 09.11.2018 / 14:13

1 answer

2

In these cases the ideal is to do with while , not that it is not possible to do with for , but for is usually used with integers.

<?php
    $data = DateTime::createFromFormat('d/m/Y', '09/11/2018'); // Define a data inicial
    $fim = DateTime::createFromFormat('d/m/Y', '16/11/2018'); // Define a data final
    $intervaloDias = 3; // Define o intervalo de dias

    while ($data->format('Y-m-d') <= $fim->format('Y-m-d')) { // Verifica se a data é menor que a data final

        echo $data->format('Y-m-d ') . "\n"; // Escreve a data na tela

        $data = $data->add(new DateInterval('P'.$intervaloDias.'D')); // Incrementa a data
    }
?>

Result

  

2018-11-09
  2018-11-12
  2018-11-15

I set up the code so that anyone can test it and see it working, so you'll need to make some changes to suit the context of your code, they're basic changes to assigning the dates to the variables.

See working at Ideone .

    
09.11.2018 / 14:49