Save for loop values to an array

Hi everyone, I would like to save the contents of a for loop into an array, but the problem is that the variable needs to be styled into a date format first. Here is my code so far:

$arrive = '1574978400';
$depart = '1575064800';

for ( $i = $arrive; $i <= $depart; $i = $i + 86400 ) {
	$bookedDates = date('Y-m-d', $i );
       // needs to be output as an array ...
}

I will then compare the resulting dates (with the following example format: 2019-11-28) with a set of dates from another array using array_intersect.

If I understand correctly…,

for ( $i = $arrive; $i <= $depart; $i = $i + 86400 ) {
$bookedDates[] = date('Y-m-d', $i );
}
echo '<pre>'; print_r($bookedDates); echo '</pre>'; // add line feeds to output
2 Likes

Yes, thank you!! That works!

1 Like

Small update to support Strict Types, removed variables for nothing, code cleanup. :grinning:

$arrive = '1574978400';
$depart = '1575158400';

for ($arrive; $arrive <= $depart; $arrive += 86400) {
    $bookedDates[] = date('Y-m-d', (int) $arrive);
}
echo '<pre>', print_r($bookedDates, true), '</pre>';   
1 Like

Alternative using DatePeriod:

$start = DateTimeImmutable::createFromFormat('U', '1574978400');
$end   = DateTimeImmutable::createFromFormat('U', '1575158400');

$period = new DatePeriod($start, new DateInterval('P1D'), $end);

$bookedDates = [];
foreach ($period as $date) {
    $bookedDates[] = $date->format('Y-m-d');
}

echo '<pre>', print_r($bookedDates, true), '</pre>';
3 Likes

Nice re-write @rpkamp.

1 Like