计算数组中的重复数量?

时间:2013-06-19 12:48:48

标签: php arrays

我有一个数组联系以下单词

(“hello”, “apple”, “hello”, “hello”, “apple”, “orange”, “cake”)

Result here should be 5

请告诉我PHP中是否有库函数可以用来计算我的数组中有多少重复的单词?任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:5)

您可以将array_unique()count()合并:

$number_of_duplicates = count($words) - count(array_unique($words));

注意: PHP有超过一百Array Functions。学习它们会让你成为better PHP Developer

答案 1 :(得分:1)

检查array_count_values http://us2.php.net/manual/en/function.array-count-values.php

<?php
var_dump(array_count_values($words));

Output:
Array(
    [hello] => 3,
    [apple] => 2,
    [orange] => 1,
    [cake] => 1
)

答案 2 :(得分:0)

试试这个

$count1 = count($array);
$count2 = count(array_unique($array));
echo $count1 - $count2;

答案 3 :(得分:0)

你可以这样做:

$org = count($array);
$unique = count(array_unique($array));
$duplicates = $org - $unique

答案 4 :(得分:0)

$array = array(“hello”, “apple”, “hello”, “hello”, “apple”, “orange”, “cake”);
$unique_elements = array_unique($array);
$totalUniqueElements = count($unique_elements); 
echo $totalUniqueElements; 
//Output 5

Hope this will help you.