I have a variable that stores current time with $current_time
and another variable with an array of time stored in $time_slot
I am looking for a way around to unset from array variable $time_slot
all array of time that is less than the $current_time
I tried below code but it didn’t work:
$current_time = '4:00';
$time_slot = ['1:00','3:00','15:00','19:00'];
// removing the deleted value from array
if (($key = array_search($current_time, $time_slot)) !== false) {
if($current_time>$time_slot){
unset($time_slot[$key]);
}
}
print_r($time_slot);
2
Answers
You can convert your timeslots to a
DateTime
instance which will make it easier to compare your values.In the snippet below, I unset the index of the timeslot if it’s "expired"
demo
demoBy making natural sorting comparisons, you can call
array_filter()
to weed out the times which are smaller than the current time.strnatcmp()
returns a 3-way result (-1
,0
, and1
) — if-1
then the the first value is smaller than the second value.You don’t need to create new DateTime objects on every iteration.
Code: (Demo)