I have these datetime input in array from 8am until 5pm
2022-09-23 08:00:00
2022-09-23 08:30:00
2022-09-23 09:00:00
2022-09-23 09:30:00
2022-09-23 10:00:00
2022-09-23 10:30:00
2022-09-23 11:00:00
2022-09-23 13:00:00
2022-09-23 13:30:00
2022-09-23 14:00:00
2022-09-23 14:30:00
2022-09-23 15:00:00
2022-09-23 16:00:00
2022-09-23 16:30:00
2022-09-23 17:00:00
2022-09-23 17:30:00
My goal is to get/output previous array if input for datetime is greater than previous array and less than next array
Input datetime 2022-09-23 09:12:00, it will use 2022-09-23 09:00:00
Input datetime 2022-09-23 10:29:00, it will use 2022-09-23 10:00:00
My current code :
$final_datetime = array();
$datetime = "2022-09-22 09:12:00";
foreach ($arr as $k => $v) {
if ($v == $datetime) {
$final_datetime[] = $v;
} else {
$next1="";
$prev1="";
// Previous Array
if (isset($arr[$k-1])) {
$prev1 = $arr[$k-1];
}
// Next Array
if (isset($arr[$k+1])) {
$next1 = $arr[$k+1];
}
$prev2 = date_create($prev1);
$prev = date_format($prev2, 'Y-m-d H:i:s');
$next2 = date_create($next1);
$next = date_format($next2, 'Y-m-d H:i:s');
if ($datetime > $prev && $datetime < $next) {
echo 'Output : '.$prev.'<br/>';
} else {
}
}
}
My current output :
Output : 2022-09-22 08:30:00
Output : 2022-09-22 09:00:00
Expected Output :
Output : 2022-09-22 09:00:00
$datetimeis>=the current array element, output it and break out of the loop at that point.