Home > Blockchain >  How to compare key's value and get value in PHP array
How to compare key's value and get value in PHP array

Time:04-13

I have an array like this

Array
(
    [10] => 0
    [30] => 2
    [90] => 5
    [365] => 10

)

Array Key have #days and value have #percentage.

Now if pass day value between 0 to 10 days then percentage will be 0, if between 11 to 30 days then percentage will be 2 if between 31 to 90 days then percentage will be 5 if 500 days then 10

My code is

    $closest = null;
    foreach ($stake as $k=>$v) {
        echo "abs($search - $closest)";
        echo "abs($k - $search)";
        if ($closest === null || abs($search - $closest) > abs($k - $search)) {
          $closest = $k;
       }
    }

but when i pass 11 it's return 10 instead of 30

CodePudding user response:

Just loop over your stakes, and check if the search value is lesser-equal the current key. If so, set that value as closest, and exit the loop.

If you still have not found one after the loop, it means the search value must have been greater than your largest key - so in that case, pick the last element.

$stakes = [10 => 0, 30 => 2, 90 => 5, 365 => 10];
ksort($stakes);
$closest = null;
$search = 11;
foreach($stakes as $threshold => $stake) {
    if($search <= $threshold) {
        $closest = $stake;
        break;
    }
}
if($closest === null) {
    $closest = end($stakes);
}
var_dump($closest);
  • Related