最后计算相同的值

时间:2013-08-11 23:41:44

标签: php arrays

我有阵列:

$array = array(1,1,5,2,3,3,3,3);

我需要找到一种方法来计算数组末尾重复数字的次数。在这种情况下,数字3重复4次。

如果......:

$array = array(1,1,5,2,3,3,3,3,4);

在这种情况下,结果为1,因为数字4只出现一次。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

试试这个:(working example

$array = array(1,1,5,2,3,3,3,3);
$num = end($array); // this will be 3 - the value to compare to
$count = 0; // init count

for($i = sizeof($array)-1; $i>=0;$i--) // loop from the end backwards
    if($array[$i]==$num) // if this is the correct num
        $count++; // increase count
    else
        break; // end loop - not side by side anymore - no reason to keep looping

echo $count; // print the result
相关问题