Return days of the year by removing the ones in a Variable

1

I need a function in PHP that returns me every day of the year except for the ones that were previously selected.

Example My client selected ( 01 / 01,02 / 01,04 / 01,12 / 01,12 / 05,18 / 01,08 / 01,10 / 11,05 / 12,11 / 09,01 / 12 )

Then I need you to manage all the remaining days to be recorded in the bank.

It can be in the same American format.

The above list is only a small example, as it can be marked up to 250 days, thus remaining a few days

    
asked by anonymous 14.06.2018 / 22:26

1 answer

2

You can solve this problem with the following steps, generating a range of dates (the calendar of the year itself) with the help of DateInterval and DatePeriod that defines the incrementing unit (PD1 ) of the range.

Then get the current day of foreach and compare it to the list of exceptions and have in_array() skip them, this will generate the SQL string with several values to execute only one insert at the end.

It is important to remark that the date range does not include the end date in the 12/31/2018 case so the line: $dataFim->modify('+1 day'); . modify() adds another day to the date that you turn 01/01/2019 .

$dataInicio = new DateTime('2018-01-01');
$dataFim = new DateTime('2018-12-31');
$dataFim->modify('+1 day');
$intervalo = new DateInterval('P1D');

$diasAno = new DatePeriod($dataInicio, $intervalo, $dataFim);

$selecionados = '01/01,02/01,04/01,12/01';
$excecoes = explode(',', $selecionados);


foreach($diasAno as $date){
    if(!in_array($date->format('d/m'), $excecoes)){
        $sql .= sprintf("('%s'),", $date->format('Y-m-d'));
    }
}

$sql = rtrim($sql, ',');
echo $sql;

Output is something like:

('2018-01-01'),('2018-01-02'),('2018-01-03'),('2018-01-04')
    
14.06.2018 / 22:53