Abdellah Chadidi
Abdellah Chadidi

Reputation: 675

How can I find the key of the highest value in an array ≤ a specific value?

I have an array that relates a user level to minimum points required for that level, like this:

$userLV = array(0 => 0, 1 => 400, 2 => 800);

The key is the level and the value is the minimum points required for that level.

If a user has a certain number of $points, I need to find their level by finding the key from the $userLV array that corresponds to its greatest value less than $points.

How can I achieve this? (The example array is PHP, but an example in JavaScript or any language will be helpful.)

Upvotes: 0

Views: 59

Answers (2)

Don't Panic
Don't Panic

Reputation: 41820

Here is one way to do it (please note that this depends on the array already being sorted in ascending order):

$level = 0;                           // start at 0
foreach ($userLV as $lv => $val) {    // loop through the levels
    if ($points >= $val) {
        $level = $lv;                 // reset the level as long as $points >= level value
    } else {
        break;                        // stop when it no longer is
    }
}

Another option, if you want to continue to increment level for every multiple of 400 is to just use math.

$level = intval($points / 400);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386868

A proposal in Javascript

function getLevel(points) {
    var level;
    [0, 400, 800].every(function (v, i) {
        if (points >= v) {
            level = i;
            return true;
        }
    });
    return level;
}

document.write([0, 200, 400, 600, 800, 1000].map(function (a) { return 'points: ' + a + ', level: ' + getLevel(a); }).join('<br>'));

Upvotes: 1

Related Questions