Home > Article > Backend Development > How to Find the Closest Value in an Array?
Closest Value Matching in an Array
Given an array of values and a target value, a common requirement is to retrieve the closest matching value in the array. This can prove particularly useful when dealing with imprecise data or when an exact match is not available.
Solution:
To determine the closest matching value, an iterative search algorithm can be employed. Here's a PHP function that implements this approach:
function getClosest($search, $arr) { $closest = null; foreach ($arr as $item) { if ($closest === null || abs($search - $closest) > abs($item - $search)) { $closest = $item; } } return $closest; }
This function operates by iteratively comparing the target value with each element in the array. It maintains a $closest variable to track the closest matching value encountered. For each comparison, it calculates the absolute difference between the target and the current array element. If the difference is smaller than the previously recorded difference, it updates the $closest variable.
Example:
Using the exemplary array provided:
$array = [0, 5, 10, 11, 12, 20];
The following searches can be performed:
By iterating through the array and evaluating each element, this algorithm efficiently finds the closest matching value to the target.
The above is the detailed content of How to Find the Closest Value in an Array?. For more information, please follow other related articles on the PHP Chinese website!