0

I've created an array with 'maximum' values in.

$management = array(
    '100' => '1',
    '500' => '2',
    '1000' => '3',
);

And created a loop to find the closest value, rounding it up.

$speed = 10;

$r= '';
sort($management);
foreach($management as $mgmt => $name) {
    if($mgmt >= $speed) {
        $r= $name;
    }
}
$r= end($management);

So, where the $speed is 10, it should pick up the array key 100 and if it was 100 it should still pickup 100 but if the speed was 200, it would pickup 500

The above is picking up 500 when the $speed is 10 though.

Can anyone help please?

charlie
  • 415
  • 4
  • 35
  • 83
  • Possible duplicate of [Find a matching or closest value in an array](https://stackoverflow.com/questions/5464919/find-a-matching-or-closest-value-in-an-array) – executable Feb 26 '19 at 10:03

3 Answers3

4

You have a couple of problems with your code. Firstly, the call to sort rewrites all the keys of the $management array which you are using for the comparison; you need to use ksort instead to sort by the keys instead of the values. Secondly, since the keys are in ascending order, once one is greater than the $speed value, they all will be, so you need to break from the loop once you find a higher value. Try this instead:

$r= '';
ksort($management);
foreach($management as $mgmt => $name) {
    if($mgmt >= $speed) {
        $r= $name;
        break;
    }
}
echo $r;

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
0

this is an example on how you can do it :

$array = array(1, 10, 100, 200, 400, 500, 1000);

public function getArrayRoundUp($array, $number) {

sort($array);
foreach ($array as $a) {

if ($a >= $number) return $a;
}
return end($array);
}

$value = 950;
$nearest = getArrayRoundUp($array, $value);
//the expect result will be 1000
echo $nearest;
Moubarak Hayal
  • 191
  • 1
  • 7
0

Use the following function

function find(array $array, $search)
{
    $last = null; // return value if $array array is empty

    foreach ($array as $key => $value) {
        if ($key >= $search) {
            return $key; // found it, return quickly
        }
        $last = $key; // keep the last key thus far
    }

    return $last;
}

Tested and Working:-

echo find($management, 100); // Will result 100
echo find($management, 200); //Will result 500
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20