我下面的话计算数组中重复的数量?
(“hello”, “apple”, “hello”, “hello”, “apple”, “orange”, “cake”)
Result here should be 5
阵列接触,你能告诉我,如果有在PHP
的库函数,我可以用它来算多少重复的单词出现在我的阵列?任何帮助将不胜感激。
我下面的话计算数组中重复的数量?
(“hello”, “apple”, “hello”, “hello”, “apple”, “orange”, “cake”)
Result here should be 5
阵列接触,你能告诉我,如果有在PHP
的库函数,我可以用它来算多少重复的单词出现在我的阵列?任何帮助将不胜感激。
$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.
@nickb感谢您改进我的文本格式 –
您可以count()
结合array_unique()
:
$number_of_duplicates = count($words) - count(array_unique($words));
注: PHP有百余Array Functions。学习它们会使你成为better PHP Developer。
尝试这样
$count1 = count($array);
$count2 = count(array_unique($array));
echo $count1 - $count2;
对不起,我认为他需要独特的数量....更新我的答案。 – Gautam3164
你可以这样做:
$org = count($array);
$unique = count(array_unique($array));
$duplicates = $org - $unique
检查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
)
尽管这不直接回答问题,但它是一种替代方法。 –
谢谢大家的detaied信息。他们都非常有帮助 –