Return all dates between two dates in an array in PHP

In PHP, you can return all dates between two given dates in an array using various approaches. The most common method involves using strtotime() and date() functions to iterate through dates.

Using strtotime() and date()

This approach converts dates to timestamps and iterates through each day ?

<?php
   function displayDates($date1, $date2, $format = 'd-m-Y' ) {
      $dates = array();
      $current = strtotime($date1);
      $date2 = strtotime($date2);
      $stepVal = '+1 day';
      while( $current <= $date2 ) {
         $dates[] = date($format, $current);
         $current = strtotime($stepVal, $current);
      }
      return $dates;
   }
   $date = displayDates('2019-11-10', '2019-11-20');
   var_dump($date);
?>
array(11) {
   [0]=>
   string(10) "10-11-2019"
   [1]=>
   string(10) "11-11-2019"
   [2]=>
   string(10) "12-11-2019"
   [3]=>
   string(10) "13-11-2019"
   [4]=>
   string(10) "14-11-2019"
   [5]=>
   string(10) "15-11-2019"
   [6]=>
   string(10) "16-11-2019"
   [7]=>
   string(10) "17-11-2019"
   [8]=>
   string(10) "18-11-2019"
   [9]=>
   string(10) "19-11-2019"
   [10]=>
   string(10) "20-11-2019" 
}

Using DateTime and DatePeriod

A more modern approach using object−oriented DateTime classes ?

<?php
   function getDateRange($startDate, $endDate, $format = 'Y-m-d') {
      $start = new DateTime($startDate);
      $end = new DateTime($endDate);
      $end = $end->modify('+1 day');
      
      $period = new DatePeriod($start, new DateInterval('P1D'), $end);
      $dates = array();
      
      foreach($period as $date) {
         $dates[] = $date->format($format);
      }
      return $dates;
   }
   
   $dateArray = getDateRange('2019-11-10', '2019-11-20');
   print_r($dateArray);
?>
Array
(
    [0] => 2019-11-10
    [1] => 2019-11-11
    [2] => 2019-11-12
    [3] => 2019-11-13
    [4] => 2019-11-14
    [5] => 2019-11-15
    [6] => 2019-11-16
    [7] => 2019-11-17
    [8] => 2019-11-18
    [9] => 2019-11-19
    [10] => 2019-11-20
)

Conclusion

Both methods effectively generate date arrays, but the DateTime/DatePeriod approach is more robust and preferred for modern PHP applications. The strtotime() method works well for simple use cases and offers more flexibility in date formatting.

Updated on: 2026-03-15T08:24:14+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements