PHP Tricks
September 1, 2022

How to find the closest number in an array?

Question: Given a number. What way to find the number closest to given in unsorted array?

Data:
Unsorted numbers array: [5, 56, 23, 1, 89, 3]
Number: 90

  
<?php

// assign data to variables

$array  = [5, 56, 23, 1, 89, 3];
$number = 90;

// calculate distances between given number and each element of array

$distances = array_map(
  function($el) use ($number) {
    return abs($el - $number);
  },
  $array 
);

//get monimal distance position

$index = array_keys($distances, min($distances))[0];

// print out closest number

echo "Closest number is: " . $array[$index];

PHP code online