Home > Software design >  Filter out time values in a flat array if less than current time
Filter out time values in a flat array if less than current time

Time:10-21

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);

CodePudding user response:

You can convert your timeslots to a DateTime instance which will make it easier to compare your values.

$date = new \DateTime('15:00');
var_dump($date);
object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2022-10-20 15:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

In the snippet below, I unset the index of the timeslot if it's "expired"

<?php

$current_time = '4:00';
$time_slot = ['1:00','3:00','15:00','19:00'];

$current_date = new \DateTime($current_time);

foreach($time_slot as  $index => $value) {
    if ($current_date > new \DateTime($value)) unset($time_slot[$index]);
}
var_dump($time_slot);

demo
demo

CodePudding user response:

By 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, and 1) -- 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)

var_export(
    array_filter(
        $time_slot,
        fn($v) => strnatcmp($current_time, $v) === -1
    )
);
  • Related