how to get filtered values from array like values between range 10-20. my array contain 10,15,18,25,88,20. i want to print only between range 10-20.
Any specific requirement? php standard array does not support range search.
I have 2 suggestions: 1) sort the array and then search for the your upper limit, anything before the upperlimit would be your results 2) traverse the array, while traversing, apply your range conditions.
There are number of way to filter array in PHP.
Using array_filter
$your_array = array(10,15,18,25,88,20);
$filtered = array_filter($your_array, create_function('$var', 'return $var >= 10 && $var <= 20;'));
var_export($filtered);
In action
If you want to change range start and range end without modifying create_function code:
$your_array = array(10,15,18,25,88,20);
$range_start = 10;
$range_end = 20;
$filtered = array_filter($your_array, create_function('$var', 'return $var >= '.$range_start.' && $var <= '.$range_end.';'));
var_export($filtered);
In action
$your_array = array(10,15,18,25,88,20);
Using foreach loop:
$filtered = array();
$range_start = 10;
$range_end = 20;
foreach ($your_array as $k=>$v) {
if ($v >= $range_start && $v <= $range_end) {
$filtered[$k] = $v;
}
}
var_export($filtered);
In action
Or so if you don't need to create new array, but modify existing one:
$your_array = array(10,15,18,25,88,20);
$range_start = 10;
$range_end = 20;
foreach ($your_array as $k=>$v) {
if (!($v >= $range_start && $v <= $range_end)) {
unset($your_array[$k]);
}
}
var_export($your_array);
In action
You can use array_filter
function range10_20($var) {
return ( $var >= 10 && $var <= 20 );
}
$input = array(10,15,18,25,88,20);
$output = array_filter($input, 'range10_20');
Or something like that:
$input = array(10,15,18,25,88,20);
$range = array(
'from' => 10,
'to' => 20
);
$output = array_filter($input, function ($element) use ($range) {
return ( $var >= $range['from'] && $var <= $range['to'] );
});
use array_intersect with range
$input = array(10,15,18,25,88,20);
$myrange = range(10,20);
$output = array_intersect($input , $myrange );
print_r($output );
DEMO