Home > Backend Development > PHP Tutorial > How to Find the Nearest Value in a PHP Array?

How to Find the Nearest Value in a PHP Array?

Barbara Streisand
Release: 2024-11-28 16:30:11
Original
927 people have browsed it

How to Find the Nearest Value in a PHP Array?

Finding Matching or Nearest Array Values

In programming, it becomes necessary to locate specific values within arrays. Particularly, finding the nearest value to a target value can be essential.

Let's consider an example array:

array(0, 5, 10, 11, 12, 20)
Copy after login

If we seek the nearest value to a target of 0, the function should return 0. Similarly, for target 3, the function should return 5, and for target 14, the nearest value in the array is 12.

To achieve this, we can utilize the following PHP function:

function getClosest($search, $arr) {
   $closest = null;
   foreach ($arr as $item) {
      if ($closest === null || abs($search - $closest) > abs($item - $search)) {
         $closest = $item;
      }
   }
   return $closest;
}
Copy after login

In this function, we iterate through each element in the array. For each element, we determine the absolute difference between the search value and the closest value or the current item. If the current difference is smaller than the previously recorded difference, we update the closest value to be the current item. Finally, the function returns the closest matching array element to the target search value.

The above is the detailed content of How to Find the Nearest Value in a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template