One of the best ways to compare times is to convert your strings to times using strtotime().
// Original array of date strings
$dates = array(
'08/29/2013 08:00',
'08/29/2013 08:10',
'08/29/2013 08:11',
'08/29/2013 12:20',
'08/29/2013 12:21',
'08/29/2013 12:21',
'08/29/2013 17:30',
);
// Make a new array of time stamps based on your strings
$dates_dt = array();
foreach($dates as $date)
$dates_dt[] = strtotime($date);
// Same idea with the dates you want to look at
$date_last1 = strtotime('08/29/2013 08:00');
$date_last2 = strtotime('08/29/2013 13:00');
$date_first1 = strtotime('08/29/2013 12:00');
$date_first2 = strtotime('08/29/2013 17:00');
Here's the magic - some pretty simple functions that return the closest date before (or the first entry), and the closest after (or the last) in your array.
function dateBefore($date, $dateArray){
$prev = $dateArray[0];
foreach( $dateArray as $d ){
if( $d >= $date )
return date("Y-m-d H:i", $prev);
$prev = $d;
}
}
function dateAfter($date, $dateArray){
foreach( $dateArray as $d ){
if( $d > $date )
return date("Y-m-d H:i", $d);
}
return date("Y-m-d H:i", end($dateArray));
}
echo dateBefore($date_last1, $dates_dt); // Outputs: 2013-08-29 08:00
echo dateBefore($date_last2, $dates_dt); // Outputs: 2013-08-29 12:21
echo dateAfter($date_first1, $dates_dt); // Outputs: 2013-08-29 12:20
echo dateAfter($date_first2, $dates_dt); // Outputs: 2013-08-29 17:30
http://codepad.org/cBYPuowt
Note
Probably a good idea to sort the array of times as well so they're for sure in order.
foreach($dates as $date)
$dates_dt[] = strtotime($date);
// Add sort here
sort($dates_dt);
http://codepad.org/jZPIEeJS