在数组php中获取小于或等于number的数字

PHP array:

$arr = array(0,15,60,120,2200);

I pass a $number = 12 with array value in function, then return value should be 0

and I pass a $number = 15 with array value in function, then return value should be 15

I was trying with below code but not luck

<?php
function get_less_value($arr, $number) {
    foreach ($arr as $val) {
        if ($val>= $number && $val < $number) return $val;
    }
    return end($arr);
}
echo get_less_value($arr, $number);

?>

Is array_filter is the method your looking for. I guess there are enough ways to do this :)

$array = [0, 15, 60, 120, 2200];
$number = 15;
$filtered = array_filter($array, function($element) use ($number) {
   return ($element <= $number);
});
// $filtered = [0, 15];

$max = max($filtered); //15

This can never be true:

if ($val>= $number && $val < $number)

I would try:

$highest = 0;
foreach ($arr as $val) {
    if($val <= $number){
       if($val >= $highest){
           $highest= $val;
       }
    }
}
return $highest;

You can search from the end if the array is sorted correctly, it's more simple to just find the first value no more than $number and return it.

$result = false;
foreach(array_reverse($arr) as $v)
{
  if($v <= $number)
  {
      $result = $v;
      break;
  }
}
if($result !== false)
  echo $result;

You can also use this function:

function get_less_value($arr, $number) {

    // Always sort the array first
    sort($arr);
    $i = 0;

    $biggest = 0;

    while ($number >= $arr[$i]) {
        $biggest = $arr[$i];
        $i++;
    }

    return $biggest;
}

echo get_less_value($arr, $number);

This is the naive solution and may work slow if your array would be very big. Have a look at search algorithms. e.g: Binary Search

Another PDF about the algorithms: http://epaperpress.com/sortsearch/download/sortsearch.pdf