得到不。 PHP中某些值之间的数组元素?

How to the find the number of array elements present in the array between 2 values in PHP .

lets say this is my array =>

$a = array(1,2,3,5,10);

I want to find the length of array between 2 values i.e. 2 and 10. So the answer will be 3 in the case. If the highest value to be searched is present in the array it should be added in count.

also length of array between 2 and 9 is 2.

Hope I am clear with my question. Any help would be appreciated.

Use array_filter() to filter the array down to the matching elements, then use count() on the resulting filtered array.

$a = array(1,2,3,5,10);
print count(array_filter($a, function($e) {return ($e>=2 && $e<=10);}));

Hope that helps.

Note: The syntax I've used here, with the embedded function, requires PHP v5.3 or higher.

[EDIT]

Turn it into a simple callable function:

$a = array(1,2,3,5,10);
print countInRange(2,10);

function countInRange($min,$max) {
    return count(array_filter($a, function($e) use($min,$max) {return ($e>=$min && $e<=$max);}));
}

See PHP manual for more info on array_filter() function.

$count = 0;
$min = 2;
$max = 10;

$a = array(1,2,3,5,10);

foreach($a as $val) {
    if($val > $min && $val <= $max) ++$count;
}

This should work, right? At least it will find all numbers, which are higher than your minimum but smaller/equal to your maximum.

Of course this also means, that an array of 1, 2, 9, 5 would return 2, since both 9 and 5 are greater than 2 and smaller than 10.

$count = 0;
for( $i = 0; $i < count($a); $i++ ) {
  if( $a[$i] <= $max && $a[$i] >= $min )
    $count++;
}
echo $count;