php – Finding duplicate values ​​in an array


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

Code example:

$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 the if

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


You don't actually 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);


Note: Now just foreach the duplicates and echo everything.

example IDEONE

Scroll to Top