How can PHP iterate through dates in an array and add missing entries with a value of "0" for each day?
To iterate through dates in an array and add missing entries with a value of "0" for each day, you can create a loop that goes through each date in the array and checks if it exists in the array. If the date is missing, add it with a value of "0". This ensures that all dates have a corresponding value in the array.
$datesArray = ['2022-01-01' => 5, '2022-01-03' => 10, '2022-01-05' => 15];
$startDate = '2022-01-01';
$endDate = '2022-01-05';
$currentDate = $startDate;
while (strtotime($currentDate) <= strtotime($endDate)) {
if (!array_key_exists($currentDate, $datesArray)) {
$datesArray[$currentDate] = 0;
}
$currentDate = date("Y-m-d", strtotime($currentDate . ' +1 day'));
}
print_r($datesArray);
Related questions
-
PHP function optimization file counting
-
PHP website conversion maintenance
-
IF-Abfrage foreach loop PHP