Home >Backend Development >PHP Tutorial >How Can I Find the Closest Value to a Target in an Array?

How Can I Find the Closest Value to a Target in an Array?

DDD
DDDOriginal
2024-12-04 03:41:11359browse

How Can I Find the Closest Value to a Target in an Array?

Searching and Identifying the Closest Value in an Array

Often, the need arises when searching for the closest value in an array based on a specified target. To address this scenario, let's examine an approach that effectively handles this problem.

Solution:

To determine the closest value to a target value within an array, we can utilize a simple algorithm:

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

In this algorithm, we iterate through the array, comparing the difference between the target and the current item to the already established closest value. If the difference with the current item is smaller, it becomes the new closest value.

Example:

Consider the example array provided:

array(0, 5, 10, 11, 12, 20)

If we search for the closest value to 3, the function will return 5. Similarly, for a target value of 14, the algorithm will identify 12 as the closest.

This algorithm efficiently finds the closest value to the target within an array, making it a reliable tool for various applications.

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

Statement:
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