How to query the closest number in php

藏色散人
Release: 2023-03-17 09:54:01
Original
1466 people have browsed it

php method to query the closest number: 1. Create a PHP sample file; 2. Get the closest number within the specified range through the "function NextRelatedNumber($number, $range){...}" method Just count.

How to query the closest number in php

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.

How to query the closest number in php?

php method to obtain the closest number within a specified range

The specific implementation method is as follows:

// Returns the next higher or lower number
function NextRelatedNumber($number, $range){  
  $r = $number % $range;
  $f = $number - $r;
  $b = round($r / $range, 0);
  return ($b == 1) ? $f + $range : $f;  
}
// Returns the next higher number
function NextHigherNumber($number, $range){  
  $r = $number % $range;
  $f = $number - $r;
  $b = ceil($r / $range);
  return ($b == 1) ? $f + $range : $f;  
}
// Returns the next lower number
function NextLowerNumber($number, $range){  
  $r = $number % $range;
  $f = $number - $r;
  $b = floor($r / $range);
  return ($b == 1) ? $f + $range : $f;  
}
// Returns the next related number from an array
function NextNumberArray($Number, $NumberRangeArray){
  $w = 0;
  $c = -1;
  $abstand = 0;
  $l = count($NumberRangeArray);    
  for($pos=0; $pos < $l; $pos++){
    $n = $NumberRangeArray[$pos];
    $abstand = ($n < $Number) ? $Number - $n : $n - $Number;
    if ($c == -1){
      $c = $abstand;
      continue;
    }
    else if ($abstand < $c){
      $c = $abstand;
      $w = $pos;
    }
  }
  return $NumberRangeArray[$w];
}
  
// Examples
// --------
// 0 10 20 30 40 50 ...
print &#39;NextRelatedNumber: &#39;;
print NextRelatedNumber(44, 10) . "\n";
// returns --> 40
// 0 20 40 60 80 100 ...
print &#39;NextHigherNumber: &#39;;
print NextHigherNumber(41, 20) . "\n";
// returns --> 60
// 0 5 10 15 20 25 30 35 ...
print &#39;NextLowerNumber: &#39;;
print NextLowerNumber(57, 5) . "\n";
// returns --> 55
// Example with Array
print &#39;NextNumberArray: &#39;;
print NextNumberArray(45, array(3, 8, 19, 34, 56, 89)) . "\n";
// returns --> 34
// (45 is between 34 and 56 but 34 is the next)
Copy after login

Recommended learning: "PHP Video Tutorial

The above is the detailed content of How to query the closest number in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template