NKYG Posted October 11, 2007 Share Posted October 11, 2007 Hello, I've been wondering about this for a few days. I have an array containing 4 numbers: $listofnumbers = array(0,15,30,45); Then there's a variable that could contain any number between 0 and 59. $actualtime = date('i'); Using the above I want to find out which of the numbers in the array is numerically closest to the value of $actualtime. So if $actualtime = 34 then I want to return the number 30 if $actualtime = 11 then I want to return the number 15 etc. I'm sure there's a simple solution but can't figure it out. Cheers Link to comment https://forums.phpfreaks.com/topic/72750-how-to-pick-the-closest-number/ Share on other sites More sharing options...
Barand Posted October 11, 2007 Share Posted October 11, 2007 try <?php $listofnumbers = array(0,15,30,45, 60); $mindiff = 99; $result = 0; $var = date('i'); foreach ($listofnumbers as $n) { $diff = abs($var-$n); if ($diff < $mindiff) { $mindiff = $diff; $result = $n==60 ? 0 : $n; } } echo $result; ?> Link to comment https://forums.phpfreaks.com/topic/72750-how-to-pick-the-closest-number/#findComment-366900 Share on other sites More sharing options...
NKYG Posted October 11, 2007 Author Share Posted October 11, 2007 Thanks Link to comment https://forums.phpfreaks.com/topic/72750-how-to-pick-the-closest-number/#findComment-366950 Share on other sites More sharing options...
sasa Posted October 11, 2007 Share Posted October 11, 2007 or tray $rounded = round($actualtime/15)*15 Link to comment https://forums.phpfreaks.com/topic/72750-how-to-pick-the-closest-number/#findComment-367099 Share on other sites More sharing options...
Recommended Posts