This question already has an answer here:
I have an array with values between 1-100. However, in case of an error, is there a way to make one final check just to be sure I skip/ignore values greater than 100 and the output is between 1-100?
</div>
This is where array_filter() comes in handy.
$lower_limit = 1;
$upper_limit = 100;
$array = array_filter(
$array,
function ($value) use ($lower_limit, $upper_limit) {
return ($value >= $lower_limit && $value <= $upper_limit);
}
);
Using array_filter is a way to it.
It will iterate through your array and filters it using the supplied function. In the end you'll get an array with only elements between 1 and 100.
$arr = array(
1, 2, 99, 201,
);
$goodArr = array_filter($arr, function($value){
return ($value >= 1 && $value <= 100);
});