Find first time that hasn't passed in array PHP

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Find first time that hasn't passed in array PHP



Let's say I have an array of times in PHP. How would I find the first time that hasn't passed yet?



For example, if the time is 3:20 PM and I have an array like this:


3:00 PM, 3:15 PM, 3:30 PM



The output would be 3:30 PM.





Sort the array, and the earliest entry is the oldest.
– Anthony
Aug 12 at 17:58





Your question needs to be improved. Read this to start.
– gview
Aug 12 at 18:00





Do you mean that you have an array of strings? $times = array("3:00 PM", "3:15 PM")?
– gview
Aug 12 at 18:03


$times = array("3:00 PM", "3:15 PM")





No, an array of timestamps. I'm just using strings to represent them in the post.
– Juniorized
Aug 12 at 18:04





You need to be precise. There is no PHP timestamp variable type. Are you talking about unix timestamps? If so, they are numeric and have intrinsic properties that are useful for sortation.
– gview
Aug 12 at 18:06





2 Answers
2



there are few way to do this but here are some steps you can use.



Step 1. Convert each element/value of time in the array to a timestamp using strtotime. (you can add today's date to the beginning of each time string to achieve this)



Step 2. Compare each element against the current time using time if the element is is greater than current time now save it too a new array.



Step 3. Find the smallest number in the new array using min .



Step 4. Convert this smallest value back to time using date.



This is a good use case, where a filter solution works well. PHP has the array_filter function that is built to derive a solution array from a source array using a filtration function callback:


// $times = array() of the strtotimes. They don't need to be sorted
$available = array();

function filterByNow($time)
return($time > strtotime('now'));


$available = array_filter(sort($times, SORT_NUMERIC), 'filterByNow');



So long as $available is not an empty array, the $available[0] element is your first time.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard