vendredi 30 janvier 2015

How to count how many duplicates an array has in Php

I'm new to Php and today I came across the rand()-function. I'd like to fill an array with numbers created with this function and then count the number of its duplicates. I already tried it a first time, but somehow I seem to be on the woodway.



<?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>";
}

?>




Aucun commentaire:

Enregistrer un commentaire