我只有一个数组有此代码,如何为15个或20个数字数组设置此代码,以便每个数组都能找到重复的数字?
<?php
function printRepeating($arr, $size)
{
$i;
$j;
echo " Repeating elements are ";
for($i = 0; $i < $size; $i++)
for($j = $i + 1; $j < $size; $j++)
if($arr[$i] == $arr[$j])
echo $arr[$i], " ";
}
$arr = array(6, 21, 54, 54, 23, 65, 48);
$arr_size = sizeof($arr, 0);
printRepeating($arr, $arr_size);
?>
答案 0 :(得分:1)
我相信the docs
已经实现了您要执行的操作$arr = array(6, 21, 54, 54, 23, 65, 48);
$countValues = array_count_values($arr); // create map of values to number of appearances
var_dump($countValues);
/*
array(6) {
[6]=>
int(1)
[21]=>
int(1)
[54]=>
int(2)
[23]=>
int(1)
[65]=>
int(1)
[48]=>
int(1)
}
*/
$duplicates = array_filter($countValues, function($value) {
return $value > 1;
}); // keep only duplicates (value > 1)
var_dump($duplicates);
/*
array(1) {
[54]=>
int(2)
}
*/
答案 1 :(得分:0)
通过使用array_count_values和array_diff,您可以获得所有重复数字。
由于键是数字,因此在内插时使用array_keys。
$arr = array(6, 65, 21, 54, 54, 23, 65, 48);
$count = array_count_values($arr);
$repeating = array_diff($count, [1]); // find what is not 1 ( 1 is unique values, anything higher is a repeating number)
echo "repeating values are " . implode(" " , array_keys($repeating));
输出
repeating values are 65 54