Home > other >  php get the nearest value to 1
php get the nearest value to 1

Time:12-26

$result_id[][] = "";
$result_total[][] = "";
foreach ($user as $key) {
    $a = 0;
    foreach ($drama as $row) {
        if ($w_average[$key['userid']][$row['id']] > 0) {
            if ($w_average[$key['userid']][$row['id']] < 1) {
                $result_id[$key['userid']][$a] = $row['id'];
                $result_total[$key['userid']][$a] = $w_average[$key['userid']][$row['id']];
                $a  ;
            }
        }
    }
}

i wanna get the positive value of w_average and the nearest value to 1.

the w_average are 0.25 and 0.33 but the output of my source code is 0.25

how to fix it? thanks

CodePudding user response:

are you sure that the value is pass as number, not as string?

$w_average = [0.25, 0.33, 1.21, -0.4];
foreach ($w_average as $row) {
    if($row < 1 && $row > 0 ) {
        echo "W_average = ".$row." -> Ok";
    } else {
        echo "W_average = ".$row." -> NO";
    }
}

Output:
W_average = 0.25 -> Ok
W_average = 0.33 -> Ok
W_average = 1.21 -> NO
W_average = -0.4 -> NO

Example:

$w_average = [0.25, 0.33, 1.21, -0.4];
$near = 0; 
foreach ($w_average as $row) {
   if($row < 1 && $row > $near) {
       $near = $row;
   } 
}
echo $near;

Output: 0.33

CodePudding user response:

You may use abs($number - $nearest) to get the distance of the value from your desire number

function closest(array $numbers, $nearest = 1) {
  $max = PHP_INT_MAX;
  foreach($numbers as $number) {
    $distance = abs($number - $nearest);
    if($distance < $max) {
      $max = $distance;
      $nearest = $number;
    }
  }
  return $nearest;
}

var_dump(closest([0.25, 0.33]));

// Result 0.33
  • Related