0

I would like to search value in an array, but exact searched value doesn't exist. Example :

$array = array (
    "A"  => 0,
    "B"  => 50,
    "C"  => 90,
    "D"  => 300,
    "E"  => 500
);

$searched_value = 80;

I would like to obtain B in this case. The function I would use is the following :

array_search($searched_value,$array,"<=")

How should I proceed ?

3 Answers3

2

Filter the array to only include items that meet your criteria.

$target = 80;

$filtered = array_filter($array, function($x) use ($target) {
    return $x <= $target;
});

Then sort it, unless it's already sorted.

sort($filtered);

The greatest value <= your search target will be the last element.

$value = end($filtered);
$key = key($filtered);

To use this approach for >= instead, just use that operator instead of <= in the array_filter callback, and use reset instead of end to get the first value rather than the last one.


This won't be ideal for large arrays that are already sorted before applying array_filter, because array_filter will iterate every element even after it begins to find values that don't meet the criteria. In that case it's better to just use foreach so that you can break out of the loop as soon as you find your target.

$key = null;
$value = 0;

foreach ($array as $k => $v) {
    if ($v > $target) {
        break;
    }
    $key = $k;
    $value = $v;
}

var_dump($key, $value);

For smaller arrays, or arrays that aren't already sorted, this won't make much of a difference.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

You can subtract your value from all array elements using array_map then filter values greater than 0 (zero) using array_filter, then take the last entry. That should be your value.

Something like this:

$array = array ( ... );
$searched_value = 80;

function subtract($val) {
    return $val - $searched_value;
}

function ltzero($val) {
    return $val <= 0;
}

$new_arr = array_filter(array_map('subtract', $array), 'ltzero');

// get last item or $new_arr
Andrei Duca
  • 372
  • 2
  • 11
-2

use if:-

if(array_search($searched_value,$array)=="") echo "not found"; else echo array_search($searched_value,$array);

wedglal
  • 1
  • 2