Morten Hagh
Morten Hagh

Reputation: 2113

round to nearest multiple of 5 in a range in php

I have this if statement:

if($_GET["angle_1"] > 39) {
    $markers["###ANGLE###"] = "45"; 
} elseif($_GET["angle_1"] > 29 && $_GET["angle_1"] < 40) { 
    $markers["###ANGLE###"] = "35"; 
} elseif($_GET["angle_1"] < 30) {
     $markers["###ANGLE###"] = "25"; 
} else { 
     $markers["###ANGLE###"] = "45"; 
}

Is there a better / simpler way to do this check, f.x. with round that will round the integer to the nearest 5, i.e. 28 -> 25 or 34 -> 35 etc. and in that, if the integer is less than 25, it will always be 25 and if the integer is higher than 45, it will always be 45 and again if the integer is between 30 and 40 it will always be 35.

That returned value will be used to display an image.

EDIT:

I have 3 images: image_25, image_35 and image_45, therefore the need to round.

Upvotes: 0

Views: 2085

Answers (2)

Geert
Geert

Reputation: 1227

Let say $x has the number:

$x = 39;

If you want the closest multiple of 5 (39 --> 40):

$x = round($x / 5) * 5;

If you want to round up (36 --> 40):

$x = ceil($x / 5) * 5;

If you want to round down (39 --> 35):

$x = floor($x / 5) * 5;

After defining $x, you can use the following to make sure its in the 25-45 range:

$x = ($x > 45) ? 45 : ($x < 25) ? 25 : $x;

Upvotes: 6

Chris
Chris

Reputation: 5605

Give this a try:

$var = 5 * round($n / 5);

Taken from here

Upvotes: 3

Related Questions