Jump to content

Round down to cloest number


jaymc

Recommended Posts

I have an array of numbers, which can change (generated by database).. so lets they they are

 

 

array(100,200,500,1000,5000,10000);

 

I want to pull out the cloest matching element in that array to a number I specify, but it must round down

 

So if I input the number 170 I want it to return 100

If I input the number 120 I want it to return 100

If I input the number 4500 I want it to return 1000

If I input the number 5200 I want it to return 5000

If I input the number 9000 I want it to return 5000

If I input the number 12000 I want it to return 10000

 

To help you understand if our customer spends £100+ they get a special discount, £500+ an even better discount, £1000+ even better discount and so on

 

So if they spend £900 they get the discount associated with spending £500+ even though £900 is closer to £1000

 

Hope you understand.

Link to comment
https://forums.phpfreaks.com/topic/178603-round-down-to-cloest-number/
Share on other sites

$number=170;
$arr=array(100,200,500,1000,5000,10000);
foreach($arr as $key=>$value) {
    if($number>$value) {
        $output=$value;
    } else {
        // I think break is the right statement?
        break;
    }
}

echo("The nearest number is ".$output);

 

This is coded without any testing, but you get my drift ;)

Archived

This topic is now archived and is 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.