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)
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; }
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!