phparraystimefilteringnatural-sort

Filter out time values in a flat array if less than current time


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


Solution

  • 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