Find duplicate values in an array

2

I have foreach and it has the same results, I want it when it has the same result it makes a echo

Code sample:

$courses = array('teste', 'teste2', 'teste3', 'teste');
foreach ($courses as $key => $course) {
     if ($course == $course) {
           echo $course;
     }
}

The second comparison variable is missing in the example, in the example I used the same $course->fullname in the 2 places of if

EDIT: I need if if I identify the two 'test' values and give a echo

    
asked by anonymous 01.11.2016 / 19:53

2 answers

4

In fact you do not need a foreach to identify duplicate values:

$courses = array('teste', 'teste2', 'teste3', 'teste');
function getDuplicates( $array ) {
    return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
}

$duplicates = getDuplicates($courses);

print_r($duplicates);

Obs: Now just make a foreach in the duplicates and echo at all.

Sample IDEONE

    
01.11.2016 / 20:37
2

It is also possible to identify the repeated elements with the array_count_values() function that returns an array, where the keys are the elements and the values the number of occurrences, so, just a foreach and an if asking is greater than one? if yes it is repeated.

$courses = array('2015', 'teste', 'teste2', 'wow', 'teste3', 'teste', 'wow');
$arr = array_count_values($courses);

foreach($arr as $key => $value){
    if($value > 1){
        echo 'valor repetido: '. $key .'<br>';
    }
}
    
01.11.2016 / 20:51