sakura14
sakura14

Reputation: 29

how to find index value from an unordered array in php

I have an array of numbers which is unordered list like this:-

 $a = array(
  '0' => '2',
  '1' => '4',
  '2' => '6'
  '3' => '8'
  '4' => '10'
);

Here, if i want to search number 8,then it should be return index value=3 ,but if i want to get value 3 which is not in array then it should return the nearest value

like 4= index value '1' and 2 =index value '0'.

How can i find this index value in php?

Upvotes: 1

Views: 377

Answers (2)

thpl
thpl

Reputation: 5910

<?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.

Upvotes: 2

Adam
Adam

Reputation: 18807

The trivial way to do it is the following:

function closest($array, $val) {
  $b=array_map(create_function('$v', 'return abs($v-'.$val.');'), $array);
  asort($b);
  return key($b);
}

echo closest(8); // returns 3

Upvotes: 1

Related Questions