$arr = array(4, 2, 3, 4, 5);
How to find the array is containing atleast 3 values which are greater than or equal to 4?
I just want to maintain a flag that the array holds 3 values equal to or greater than 4.
Using array_reduce
:
$total = array_reduce($arr, function($num, $val) {
if ($val >= 4) $num++;
return $num;
}, 0);
Iterate the array, set the value to a counter.
$counter = 0;
$hasMoreThan3 = false;
foreach($array as $element) {
if($element > 3) {
$counter++;
if($counter >= 3) {
$hasMoreThan3 = true;
break;
}
}
}
var_dump($hasMoreThan3);
If the array is short, you can filter
count(array_filter($array, function($e) {
return $e > 3;
}));
You could do it like this :
$arr = array(4, 2, 3, 4, 5);
var_dump(threeValuesOver($arr, 3));
function threeValuesOver($array,$value){
$counter = 0;
foreach($array as $entry){
if($entry > $value) $counter++;
if($counter >= 3) return true;
}
return false;
}
Here is fast simple code:
$arr = array(4, 2, 3, 4, 5);
$countval = 0;
foreach($arr as $val) {
$countval+=($val >=4)?1:0;
}
$flag = ($countval>2);
It will count values equal or greater 4 and if it counts 3 or more it will echo.
Try this another code:
$arr = array(4, 2, 3, 4, 5);
//--- 1
$arrdif = array(0, 1, 2, 3);
$flag = (count(array_diff($arr, $arrdif))==3);
//--- 2
rsort($arr, SORT_NUMERIC);
$flag = (array_search(3, $arr)==3);
This is the simple solution after optimizing 'msg' solution
$bool = array_reduce($arr, function($num, $val) {
if ($val >= 4) $num++;
return $num;
}, 0) >= 3;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.