user1421214
user1421214

Reputation: 909

Matching a closest number

I have a series of numbers from 0 to 59 which are listed to a given step value. For example if I have Step value is 5 then the series become.

0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55

(or if the Step was 3, it'd become 0, 3, 6, 9, 12 .... 59 etc etc)

Now I need to find the closest match on a given user number. For example, if I the user number 18,19 or 20 then the closest match is 20. If the user number is 16,17 then it's 15. I am assuming this examples for step value of 5. But if it could be for any step value, then that would be great.

How do I do that?

$step = 5; 
$usernumber = 18;
$myseries = range(0, 59, $step);
foreach($myseries as $num) {
  echo $num.'<br />';

  //if($usernumber is close to $num) { 
  //      echo 'Matching number is '.$num;
  //}
}

Upvotes: 0

Views: 132

Answers (3)

KristofMorva
KristofMorva

Reputation: 649

If your series won't have any holes (like 8, 9, 11), then you don't need to iterate through the whole array. It is only a draft, so not sure if it's 100% correct, but I hope it can help:

$usernumber = 18;
$min = 0;
$max = 60;
$step = 5;

$r = $usernumber % $step;
if ($r > $step / 2) {
    $num = $usernumber + ($step - $r);
    if ($num > $max) {
        $num = $max - $max % $step;
    }
}
else {
    $num = $usernumber - ($step - $r);
    if ($num < $min) {
        $num = $min + $step - ($min % $step);
    }
}
echo $num;

Upvotes: 0

krishna
krishna

Reputation: 4099

try this

$step = 5; 
$usernumber = 188;
$myseries = range(0, 59, $step);

$myseries = range(0, 59, 5);

$check = round($usernumber/$step) * $step;

if(in_array($check,$myseries))
    echo "<br>".$check;
else
    echo max($myseries);

Demo

Upvotes: 0

Kiwi
Kiwi

Reputation: 2816

What about $step * round($usernumber / $step) ?

You will need to check bounds of $usernumber and give it as a floating-point number for the division.

Upvotes: 3

Related Questions