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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.