PHP:检查,哪些数组值大于1(重复等)

时间:2012-12-07 22:20:53

标签: php arrays string

有一个数组:

Array
(
    [Apple] => 1
    [Banana] => 2
    [Orange] => 1
    [Pie] => 3
)

我想检查一下,哪些数组值大于1(重复等)并返回它们。

'Banana was found 2 times in the array, Pie even 3 times.

2 个答案:

答案 0 :(得分:2)

您可以使用array_filter根据键/值过滤数组。它返回的数组只包含与回调函数中的条件匹配的数组。

$greaterThanOne = array_filter($array, function($val){ return ($val > 1); });

foreach($greaterThanOne as $fruit=>$count){
    echo "$fruit was found $count times in the array.<br>";
}

答案 1 :(得分:0)

你只需要迭代数组......

foreach ($array_with_fruits as $fruit=>$times){
    if ($times>1) { echo $fruit." was found ".$times." times"; }
}