Show next value of an Array based on previously found value

Asked

Viewed 47 times

0

I cannot show sequence element of a timed array.

I created a variable $hora that stores the local time, and an array with several times $os, then I search for an equal time, if it shows, but if you don’t want to show the next time.

Look what I’ve done:

$hora = date('Hi');
$os = array('1632','1635','1638','1654','1642');

    if( in_array($hora, $os)){

        echo "Proximo onibus as : " . $hora;
    }else{

        echo  // Comparar e dar o valor subsequente ao valor da hora 
              // encontrada
    }

};

Any suggestions?

  • What if there is no subsequent value? What should happen?

  • In fact this array will be a "table" with bus schedules, in case you don’t think I should put another Else at the end with some msg. Ex: now it is 17:47 , suppose the guy consulted and and the last value was 17:45, then he shows the next value by ex 18:00 ..

  • Leo, see this post: Get Next. Should help you.

2 answers

1


Pay attention to time differences/timezones with the server or values stored in the database.

Try this:

$hora = date('Hi');
$os = array('1632','1635','1638','1654','1642');

// pega o próximo
sort($os); // caso garanta que $os estará ordenado, pode tirar essa linha
$proximo = '';
foreach ($os as $h) {
    if ($h - $hora >= 0) {
        $proximo = $h;
        break;
    }   
}

// mostra mensagem
if (empty($proximo)) {
    echo "Não haverá mais ônibus após esse horário hoje";
} else {
    echo "Próximo ônibus: " . $proximo;
}
  • worked that’s just what I needed! Thank you!

  • @Leo :) You’re welcome!

0

This is the simplest way I’ve found:

<?php

$hora = date('Hi');
$os = array(1632,1635,1638,1654,1642,2200,2300,2305,2308,2310,2320,2330 );

foreach($os as $o){
// echo "<li>$o";
  if($hora == $o){
    echo "<p>O horário foi encontrado: " . $o ."</p>";
    break;
  }
  if($o > $hora){
    echo "<p>O horário não foi encontrado, mas o próximo é: ".$o." </p>";
    break;
  }

}

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.