Home  >  Article  >  Backend Development  >  How to Find the Closest Value in an Array?

How to Find the Closest Value in an Array?

DDD
DDDOriginal
2024-11-26 21:49:14713browse

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:

  • getClosest(0, $array); // returns 0
  • getClosest(3, $array); // returns 5
  • getClosest(14, $array); // returns 12

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!

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