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

时间:2017-03-31 17:13:44

标签: php arrays

需要计算等于或高于5的值。这是我最好的猜测,但它甚至还没有接近工作。

$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;
}

3 个答案:

答案 0 :(得分:0)

替换你的循环
foreach($array as $thing)
    if($thing >=5){
            $x += 1;
    }
}

答案 1 :(得分:0)

以下是将添加大于5的所有数字的代码,并将它们存储在单独的数组中;

<?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));

答案 2 :(得分:0)

只是为了好玩:

$count = count(array_filter($array, function($v){ return ($v >= 5); }));
  • 过滤掉值&lt; 5
  • 计算其余的

或者如果你想循环和回声:

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

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