在数组中显示高于特定数字的值并计算有多少值

问题描述:

Need to count how many values that are equal or above 5. This is my best guess, but it's not even close to working.

$array = array(1,4,8,1,4,10,5,6,2,4,6);
$x=0;

while ($x < count($array)){
    if($array[$x]>=5){
        $amount = array_count_values($array[$x]);
        echo $amout;
    }
    $x += 1;
}

The following is the code that will add all the numbers greater than 5, and also store them in a separate array;

<?php
$array = array(1,4,8,1,4,10,5,6,2,4,6);
$count=0;
$arr2 = [];
foreach($array as $arr)
{
    if($arr >= 5)
    {
        $count++;
        $arr2[] = $arr;
    }
}


echo "Total Greater than 5 = ".$count;
echo "Greater than 5 values:";
print_r($arr2);
echo "Total less than 5 = ".(count($array)-count($arr2));

Replace your loop with

foreach($array as $thing)
    if($thing >=5){
            $x += 1;
    }
}

Just for fun:

$count = count(array_filter($array, function($v){ return ($v >= 5); }));
  • filter out values < 5
  • count the remaining ones

Or if you want to loop and echo:

$result = array_filter($array, function($v){ return ($v >= 5); });

foreach($result as $number) {
    echo "$number<br>";
}