skip to Main Content

I have a specific array with the following data:

time_plan = ['06:00:00', '06:20:00', '06:40:00', '07:00:00', '07:20:00',
  '07:40:00', '08:00:00', '08:20:00', '08:40:00', '09:00:00',
  '09:25:00', '09:50:00', '10:15:00', '11:05:00', '11:30:00',
  '12:20:00', '12:45:00', '13:35:00', '14:00:00', '14:50:00',
  '15:15:00', '15:40:00', '16:05:00', '16:25:00', '16:45:00',
  '17:05:00', '17:25:00', '17:45:00', '18:05:00', '18:25:00',
  '18:45:00', '19:05:00', '20:05:00', '21:05:00', '22:05:00',
  '23:05:00']

I want to only extract the time value (only one) that is more than current time only. If the current time is 11:35:00, then i want to extract and print only 12:20:00 from the array. How do i do that? I have tried the following but its not working:

$time_now refers to current time.

foreach($data as $time_plan){
            if($data >= $time_now){
                print_r($data);
            }
        }

2

Answers


  1. Your codes have multiple errors, here is the fix:

    $time_plan = ['06:00:00', '06:20:00', '06:40:00', '07:00:00', '07:20:00',
      '07:40:00', '08:00:00', '08:20:00', '08:40:00', '09:00:00',
      '09:25:00', '09:50:00', '10:15:00', '11:05:00', '11:30:00',
      '12:20:00', '12:45:00', '13:35:00', '14:00:00', '14:50:00',
      '15:15:00', '15:40:00', '16:05:00', '16:25:00', '16:45:00',
      '17:05:00', '17:25:00', '17:45:00', '18:05:00', '18:25:00',
      '18:45:00', '19:05:00', '20:05:00', '21:05:00', '22:05:00',
      '23:05:00'];
      
      foreach($time_plan as $data) {
          if(strtotime($data) >= strtotime('11:35:00')) {
              // $data is not an array, don't use print_r()
              echo $data . PHP_EOL;
              break;
          }
      }
    

    which prints:

    12:20:00
    
    Login or Signup to reply.
  2. Break out of loop after first one.

    <?php
    $time_plan = ['06:00:00', '06:20:00', '06:40:00', '07:00:00', '07:20:00',
      '07:40:00', '08:00:00', '08:20:00', '08:40:00', '09:00:00',
      '09:25:00', '09:50:00', '10:15:00', '11:05:00', '11:30:00',
      '12:20:00', '12:45:00', '13:35:00', '14:00:00', '14:50:00',
      '15:15:00', '15:40:00', '16:05:00', '16:25:00', '16:45:00',
      '17:05:00', '17:25:00', '17:45:00', '18:05:00', '18:25:00',
      '18:45:00', '19:05:00', '20:05:00', '21:05:00', '22:05:00',
      '23:05:00'];
    
    $time_now = "11:35:00";
    
    foreach ($time_plan as $data) {
        if ($data > $time_now) {
            echo $data;
            return;
        }
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search