如何计算数组在 Php 中有多少重复项

How to count how many duplicates an array has in Php

我是 Php 的新手,今天我遇到了 rand() 函数。我想用这个函数创建的数字填充一个数组,然后计算它的重复项数。我已经第一次尝试过了,但不知何故我似乎在木路上。

<?php

$numbers = array();


for ($i=0; $i < 100; $i++) { 
    $numbers[$i] = rand(0, 100);
}

//$numbers = array(12,12,12,12);
echo "random numbers generated.<br>";

$arrLength = count($numbers);
$arrWithDoubles = array();

for ($i=0; $i < $arrLength; $i++) {
    //echo "start looping for i: ".$i."! numbers['i'] has the content".$numbers[$i].".<br>"; 
    for ($x=$i; $x < $arrLength; $x++) { 
            //echo "looped for x: ".$x."! numbers['x'] has the content".$numbers[$x].".<br>";
        if($numbers[$i] == $numbers[$x]) {
            if($i != $x) {
                //echo "pushed to 'arrWithDoubles'.<br>";
                array_push($arrWithDoubles, $numbers[$x]);
            }
        }
    }
}

echo "numbers of doubles: ".count($arrWithDoubles)."<br>";
echo "list of numbers which were double:<br>";
for ($i=0; $i < count($arrWithDoubles); $i++) { 
    echo $arrWithDoubles[$i];
    echo "<br>";
}

 ?>

array_unique() 函数从数组中删除重复项,然后只需添加一些数学运算。

<?php

$numberOfDuplicates = count($orginalArray) - (count($orginalArray) - count(array_unique($originalArray)));

?>
$origin = array(2,4,5,4,6,2);
$count_origin = count($origin);
$unique = array_unique($origin);
$count_unique = count($unique);

$duplicates = $count_origin - $count_unique;

echo $duplicates;
$count = array();
foreach ($srcRandom as $sr) {
    if (!array_key_exists ($sr, $count) ) {
        $count[$sr] = 1;
        continue;
    }
    $count[$sr]++;
}
var_dump ($count);

感谢您的所有意见。有了这个,我得出了以下最符合我需求的解决方案:

<?php

function countValueInArray($value, $array) {
    $count = 0;
    for ($i=0; $i < count($array); $i++) { 
        if($value == $array[$i]) {
            $count++;
        }
    }
    return $count;
}

$numbers = array();

for ($i=0; $i < 100; $i++) { 
    $numbers[$i] = rand(0, 100);
}

$duplicates = array();
for ($x=0; $x < count($numbers); $x++) { 
    $number = countValueInArray($numbers[$x], $numbers);

    if ($number > 1) {
        array_push($duplicates, $numbers[$x]);
    }
}

$duplicatesList = array_values(array_unique($duplicates));

echo "number of duplicates: ".count($duplicatesList);
echo "<br>these are: <br>";

print_r($duplicatesList);

?>

非常感谢您的帮助!