Find duplicate values in an array

Asked

Viewed 7,136 times

3

I have a foreach and he has equal results, I want that when he has the same result he make a echo

Code example:

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

Missing in the example the second comparison variable, in the example I used the same $course->fullname in the 2 if places

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

  • 1

    Edit your code as you are doing it, please.

  • 1

    Does this second variable have its value changed? is a foreach inside another?

  • Edit the question and mount a closer example of the real code if you can’t show it. You can even suggest a array_intersect() or related.

  • I put together another example... @rray

  • The goal is to find equal values in an array?

  • yes!!!!!!!!!!!!

Show 1 more comment

2 answers

6

Actually you don’t need one 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 do one foreach in duplicates and give echo in everything.

IDEONE OF EXAMPLE

3

It is also possible to identify the repeated elements with the function array_count_values() that returns an array, where the keys are the elements and the values the number of occurrences, with that, just a foreach and a asking if is greater than one? if yes 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>';
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.