0

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;
  //}
}
user1421214
  • 909
  • 4
  • 17
  • 24

3 Answers3

3

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.

Kiwi
  • 2,698
  • 16
  • 15
0

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

krishna
  • 4,069
  • 2
  • 29
  • 56
0

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;
KristofMorva
  • 639
  • 1
  • 7
  • 13