Create an Array of Dates Between Two Dates in PHP

please click here for more wordpress cource

To create an array of dates between two dates in PHP, you can use the DateTime and DateInterval classes. Here’s an example function that will generate an array of dates:

function createDateRangeArray($startDate, $endDate) {
    $dates = array();

    $currentDate = new DateTime($startDate);
    $endDate = new DateTime($endDate);

    while ($currentDate <= $endDate) {
        $dates[] = $currentDate->format('Y-m-d');
        $currentDate->add(new DateInterval('P1D'));
    }

    return $dates;
}

Here, $startDate and $endDate are strings representing the start and end dates of the range you want to generate. The function creates an empty array called $dates, creates a DateTime object for the start date, and a DateTime object for the end date.

It then loops through the dates from the start date to the end date using the while loop. In each iteration, it adds the current date to the $dates array, formats the date as a string using the format method, and adds one day to the current date using the add method.

Finally, the function returns the array of dates.

Here’s an example usage of the function:

$startDate = '2022-03-01';
$endDate = '2022-03-10';

$dates = createDateRangeArray($startDate, $endDate);

print_r($dates);

Output:

Array
(
    [0] => 2022-03-01
    [1] => 2022-03-02
    [2] => 2022-03-03
    [3] => 2022-03-04
    [4] => 2022-03-05
    [5] => 2022-03-06
    [6] => 2022-03-07
    [7] => 2022-03-08
    [8] => 2022-03-09
    [9] => 2022-03-10
)

As you can see, the function generates an array of dates between the start and end dates.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *