3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php // Date intervals gaps // date intervals as input (add as many as needed) $dates = array( array('01-01-2001', '31-01-2001'), array('10-02-2001', '20-02-2001'), array('31-12-2000', '30-03-2001') ); // end of input area if (!count($dates)) { echo 'No date intervals were given! <br />'; return; } $input_errors = 0; $intervals = array(); // build $intervals array with valid dates from input foreach ($dates as $i => $date) { if (!strtotime($date[0]) || !strtotime($date[1])) { $input_errors++; echo "Input error for $date[0] - $date[1] (#$i date interval). <br />"; continue; } $intervals[] = array( 'start' => date('d-m-Y', strtotime($date[0])), 'end' => date('d-m-Y', strtotime($date[1])) ); } if ($input_errors) { echo 'The given date intervals contain input error(s), as listed above, thus date gaps verification can not be performed. <br />'; echo 'For a retry, please correct the input date intervals or set a date after 1970 and before 2038. <br />'; return; } // sort $intervals array by start date of each interval $sorted = usort($intervals, "sortByStartDate"); if (!$sorted) { echo 'Error sorting intervals by start date. Exiting... <br />'; return; } print_r($sorted); // $start is the smallest start date of all intervals $start = $intervals[0]['start']; // $end is the biggest end date of all intervals $end = $intervals[0]['end']; $prev_end = $intervals[0]['end']; $total = count($intervals); $gaps = array(); if ($total == 1) { echo 'Only one date interval given, thus no gaps exist. <br />'; return; } // starting from the 2nd interval, check for gaps between $start and $end for ($j = 1; $j < $total; $j++) { if ($start > $intervals[$j]['start']) { $start = $intervals[$j]['start']; } if ((strtotime($intervals[$j]['start']) > strtotime($prev_end)) && (strtotime($end) < strtotime($intervals[$j]['start']))) { $gaps[] = array( 'start' => $prev_end, 'end' => $intervals[$j]['start'] ); } $prev_end = $intervals[$j]['end']; if ($end < $intervals[$j]['end']) { $end = $intervals[$j]['end']; } } echo "The smallest start date of all intervals is $start. <br .>"; echo "The biggest end date of all intervals is $end. <br />"; if (!count($gaps)) { echo 'The given date intervals do not contain gaps. <br />'; } else { echo 'The given date intervals contains the fallowing gaps: <br />'; foreach ($gaps as $gap) { echo '[ '. $gap['start'] . ' , ' . $gap['end'] . ' ] <br />'; } } // function used for sorting the $intervals array function sortByStartDate($a, $b) { if ($a['start'] == $b['start']) { return 0; } return ($a['start'] < $b['start']) ? -1 : 1; }
Output for 5.6.0 - 5.6.30, hhvm-3.18.5 - 3.22.0, 7.0.0 - 7.3.0rc3
1The smallest start date of all intervals is 01-01-2001. <br .>The biggest end date of all intervals is 31-01-2001. <br />The given date intervals contains the fallowing gaps: <br />[ 31-01-2001 , 10-02-2001 ] <br />