I have the following PHP code that iterates through a DatePeriod between a start and end date:
//Start = 01/12/2023 09:50:00
//End = 07/12/2023 13:54:00
$test = [];
$datePeriod = new DatePeriod(new DateTimeImmutable('2023-12-01'), new DateInterval('P1D'), new DateTimeImmutable('2023-12-07'));
foreach ($datePeriod as $day) {
$formattedDate = $day->format('Y-m-d');
if ($formattedDate === key($datePeriod)) {
$test[$formattedDate] = ['09:50:00-23:59:59'];
} else if ($formattedDate === end($datePeriod)) {
$test[$formattedDate] = ['00:00:00-13:54:00'];
}else{
$test[$formattedDate] = [];
}
}
I want to populate an array based on the iteration, considering specific time ranges. The working hours at the office are from 09:00 to 17:00.
I need to identify the first and last iteration and adjust the array accordingly. The desired output should be:
Array
(
[2023-12-01] => Array
(
[09:50:00-23:59:59]
)
[2023-12-02] => Array
(
)
[2023-12-03] => Array
(
)
[2023-12-04] => Array
(
)
[2023-12-05] => Array
(
)
[2023-12-06] => Array
(
)
[2023-12-07] => Array
(
[00:00:00-13:54:00]
)
)
The current output is :
Array
(
[2023-12-01] => Array
(
)
[2023-12-02] => Array
(
)
[2023-12-03] => Array
(
)
[2023-12-04] => Array
(
)
[2023-12-05] => Array
(
)
[2023-12-06] => Array
(
)
)
How can I identify the first and last iterations?
I’m using PHP 8.3
fiddle : https://onlinephp.io/c/9b183
>Solution :
How can I identify the first and last iterations?
DatePeriod already comes with properties start and end – so if you make it include the end date, with theDatePeriod::INCLUDE_END_DATE option, you can do it directly using those:
$datePeriod = new DatePeriod(
new DateTimeImmutable('2023-12-01'),
new DateInterval('P1D'),
new DateTimeImmutable('2023-12-07'),
DatePeriod::INCLUDE_END_DATE
);
foreach ($datePeriod as $day) {
$formattedDate = $day->format('Y-m-d');
if ($day == $datePeriod->start) {
$test[$formattedDate] = ['09:50:00-23:59:59'];
} else if ($day == $datePeriod->end) {
$test[$formattedDate] = ['00:00:00-13:54:00'];
}else{
$test[$formattedDate] = [];
}
}