Jump to content

Recommended Posts

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

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;
?>

Guest
This topic is now closed to further replies.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.