Jump to content

[SOLVED] Nearest highest number


wwfc_barmy_army

Recommended Posts

I think this should work. I havn't been able to test it though so let me know if there is any problems.

 

<?php
$numberArray = array(80,100, 120, 160);
$inNumber = 85;
$nearHighNum = 0;

foreach($numberArray as $value) {

if($value >= $inNumber && ($value <= $nearHighNum || $nearHighNum < $inNumber))
	$nearHighNum = $value;
}

echo $nearHighNum;
?>

Link to comment
Share on other sites

should work, but will continue testing values unnecessarily, when it has already found the number.

 

$numberArray = array(80,100, 120, 160);
$inNumber = 85;

foreach($numberArray as $value) {
    if($value > $inNumber) {
        $nearHighNum = $value;
        break;
    }
}

echo $nearHighNum;

Link to comment
Share on other sites

Very true. Just a quick note though, if the array isn't hard coded and it can come through in any random order, the coder will have to make sure that the array is in the correct order first for it work, but thats not to much hastle.

 

i.e if the array looks like this, then it will report 120 instead of100 if you pass it 85.

 

$numberArray = array(120, 80, 100, 160);

Link to comment
Share on other sites

Very true. Just a quick note though, if the array isn't hard coded and it can come through in any random order, the coder will have to make sure that the array is in the correct order first for it work, but thats not to much hastle.

 

i.e if the array looks like this, then it will report 120 instead of100 if you pass it 85.

 

$numberArray = array(120, 80, 100, 160);

 

Yeah but can sort that easily with...

 

sort($numberArray);

Link to comment
Share on other sites

Yeah but can sort that easily with...

 

sort($numberArray);

 

But that will be slower. sort() uses the quicksort algorithm, so it has a complexity of O(n*log(n)). Just going through all the elements unsorted from the start is a linear search which is O(n).

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.