<?php
function array_search_closest($needle, $haystack)
{
$closest = null;
foreach( $haystack AS $key => $value )
{
if( $closest === null || abs($needle - $value) < $closest[0] )
$closest = [abs($needle - $value), $key];
}
return $closest[1];
}
$array = [6,2,10,4,8];
echo array_search_closest(3, $array); //Output: 1
The basic functionality of that logic is to find the lowest absolute value between the needle and each of the items in the array. That value is stored into the $closest array.
The first iteration always sets the absolute value (we need something to check against). After that $closest is only overwritten if the absolute value between $needle and the value of the current iteration is lower than that of the last iteration. We eventually get lowest value, which we want.
We eventually return the key of that value.
Note that $closest is actually an array. The first element represents the current closest value of the $haystack while the last element is the key that you want.