jmatesic
jmatesic

Reputation: 13

repeating numbers array, php

I have this code for just one array, how to set this code for etc 15 or 20 arrays of numbers, for each array to found repeating number?

<?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);
?>

Upvotes: 0

Views: 649

Answers (2)

Andreas
Andreas

Reputation: 23958

By using array_count_values and array_diff you can get all the repeating numbers.
Since the key is the number I use array_keys when imploding.

$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));

Output

repeating values are 65 54

https://3v4l.org/V7d7d

Upvotes: 0

Theofanis
Theofanis

Reputation: 637

I believe what you are trying to do is already implemented by array_count_values

$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)
}
 */

Upvotes: 1

Related Questions