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

How to Find the Closest Value in an Array?

DDD
Release: 2024-11-26 21:49:14
Original
807 people have browsed it

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;
}
Copy after login

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];
Copy after login

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!

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