如何找到小于400的近似数?

时间:2014-11-15 13:29:13

标签: php

我想最接近400。意味着输出为300

$a=200;

$b=300;

$c=400;

$d=500;

$e=600;

$f=700;

$arr=array($a,$b,$c,$d,$e,$f);

5 个答案:

答案 0 :(得分:0)

您可以使用函数来查找此值:

function nearest($array, $number) {

    rsort($array);
    foreach ($array as $a) {
        if ($a < $number) return $a;
    }
    return end($array); // or return NULL;
}

输出(通过调用echo nearest($arr, 400)):

300

答案 1 :(得分:0)

试试这个!

$checkingValue= 400;
$nearestVal = 0;
$arr=array(100,200,300,500);
foreach($arr as $key=>$val)
{
    if($val <= $checkingValue){
        $nearestVal = $val;
    }else{
        break;
    }
}

echo $nearestVal; //prints 300

答案 2 :(得分:0)

您只需使用array_search()代替loop即可。例如:

$key = array_search (400, $arr);
echo isset($arr[$key - 1]) ? $arr[$key - 1] : 'Not found!';

答案 3 :(得分:0)

<?php
$a=200;
$b=300;
$c=400;
$d=500;
$e=600;
$f=700;
$arr=array($a,$b,$c,$d,$e,$f);
$number=400;
$req_no=null;
foreach ($arr as $value) {
    if ($value<$number&&$req_no<$value) {//Checking if array element is less than 400 as well as greater than the previous result.
        $req_no=$value;
    }
}
//Checking if We Have got Any result.
if($req_no!=null){
    echo $req_no;
}else{
    echo "not Found";
}

答案 4 :(得分:0)

使用array_reduce的方式:

$val = 400;
$result = array_reduce($arr, function ($c,$i) use ($val) {
    return ($i<$val && $i>$c)? $i:$c;
});