我有一个数组联系以下单词
(“hello”, “apple”, “hello”, “hello”, “apple”, “orange”, “cake”)
Result here should be 5
你能告诉我是否有一个库函数PHP
可以用来计算我的数组中有多少重复的单词?任何帮助将不胜感激。
您可以array_unique()
结合count()
:
$number_of_duplicates = count($words) - count(array_unique($words));
注意: PHP 有一百多个数组函数。学习它们将使您成为更好的 PHP 开发人员。
检查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
)
像这样试试
$count1 = count($array);
$count2 = count(array_unique($array));
echo $count1 - $count2;
你可以这样做:
$org = count($array);
$unique = count(array_unique($array));
$duplicates = $org - $unique
$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.