Question

I'm new to PHP and have I problem right now. I want to make a file with bus times for a day, and want to show a user the nearest bus in the future. Every day there are just 15 buses, so it wouldnt be a big file. I thought about saving the file like this: 0120, 0230, 1020,1340 and so on. MY thinking right now is to read from this file by fgetcsv with a for loop and store all times in an array which are > than date("His"). This would happen in the controller. In my file which shows the output to the user I would then show the first element of the array in big font as the next bus and the next 10 elements in a smaller font. Would this work? I am not sure with my time format. Can I compare 0230 from a text file with the output from date()?

Thanks for your help!

Edit: Based on the comments below I tried this. Based on my understanding this should read in one element of the csv every iteration of the while loop, right?

<?php
$buses = 0;
$hoursMins = date("Gi");
$times = [];
if (($handle = fopen("1.csv", "r")) !== FALSE) 
{
    while (($element = fgetcsv($handle, 200, ",")) !== FALSE) 
    {
        if($hoursMins < $element)
        {
            $times = $element;
            echo $times[$buses++] . "<br />\n";
            $buses++;
        }

    }
    fclose($handle);
}
?>

This is only showing me 755 though.

Was it helpful?

Solution 2

Yes, you can. To get the current time as hours/minutes in 24-hour format, just use something like this:

$hoursMins = date('Gi');

If you run this statement at, say, 2:06PM you'll get 1406. If you run it at 7:15AM you'll get 715.

Full disclosure: I originally had the format string as Hi but as bparise correctly explains in another answer, Gi is better.


To read a small file like yours, use the file_get_contents function to suck the entire file into a string:

$timesList = file_get_contents('1.csv');

From there, you can "explode" it into an array:

$times = explode(',', $timesList);

Then you can just loop through the array and look for the time that's greater than or equal to the current time. As for the current time, you might be better off with the Gi format in the date call as mentioned in another answer because it won't have a leading zero if the hour is less than 10AM.

OTHER TIPS

I would suggest to instead use date("Gi"). The "G" represents 24-hour format of an hour without leading zeros. The leading zero can cause a lot of weird issues since they are considered base8 numeric values:

var_dump(0200); // int(128)

Although date() and fgetcsv() will return strings, NOT doing zero-padded strings can only save you from possible issues if you ever cast those values as a numeric type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top