0

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);
?>
3
  • Put call to printRepeating($arr, $arr_size); in a loop Commented Aug 2, 2018 at 12:35
  • 1
    What about array_count_values? Commented Aug 2, 2018 at 12:38
  • Do you mean repeating numbers for all the combined arrays or do you just want to run this 15 or 20 times ? Commented Aug 2, 2018 at 12:49

2 Answers 2

1

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)
}
 */
Sign up to request clarification or add additional context in comments.

1 Comment

@jmatesic does this helps you or is there a different problem?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.