Mark the day of each week by repeating a number of times

Asked

Viewed 24 times

0

I am making a schedule and need to create a form where repeat a number of times the day of each week.

Example:

Today 09/11/2018

I want you to repeat three times a day of the week?

09/11/2018

16/11/2018

23/11/2018

My code is like this, but I’m not getting it, I used for for example as a repetition structure. How could I do this?

for ($contador = 0; $contador < 3; $contador++) {

    $data2 = str_replace("-", "/", date('Y-m-d'));

$data= date('d/m/Y', strtotime($data2));     

echo $data."<br>";  

$data = DateTime::createFromFormat('d/m/Y', $data);
$data->add(new DateInterval('P7D')); // 7dias
echo $data->format('d/m/Y');

}

1 answer

3


The algorithm is simple, you need:

  1. Create an initial date
  2. Printar data
  3. Adds 1 week
  4. Go back to step 2 until repetitions are sufficient

Example:

<?php

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

do {
    echo $hoje->format('d/m/Y') . "\n";  // Printa data
    $hoje = $hoje->add($semana);         // Adiciona uma semana
} while (--$repeticoes);

Repl.it with working code

  • I changed to use the loop do {...} while(). Makes more sense in this context

Browser other questions tagged

You are not signed in. Login or sign up in order to post.