PHP Program to find the duplicate elements in the array


April 27, 2022, Learn eTutorial
1716

Duplicate elements in the array

In this program, we are going to find the duplicate elements in the array. To find the duplicate elements we have to compare every element of the array with each other and print the element which repeats. For example, the array is 5,9,8,8,7,5,4,9,1  then the output will be 5,9,8.

How to find the duplicate elements in the array using PHP?

For this program to find the duplicate elements in the array we are taking the static values which are assigned to the array a[]. Then we have to assign the size of the array into the variable len using the built-in function count() and after that, we have to assign the value 0 into the variable i and perform the loop until the condition 'i < len' and also increment the value of the variable i in every iteration and in the loop block we have to assign the value 'i + 1' into the variable j and perform the loop until the condition 'j < len' and also increment the value of the variable j in every iteration and in the loop block check the condition 'a[i] == a[j]' if true  print the element of array 'a[j]'

ALGORITHM

Step 1: Initialize an array a[] with values

Step 2: Assing the size of an array into the variable len using the built-in function count()

Step 3: Print the element in the array a[]

Step 4: Assign the value 0 into the variable i and perform step 5 until the condition 'i < len' becomes false and increment the value of variable i in every iteration

Step 5: Assign the value 'i + 1' into the variable j and perform the sub-steps until the condition 'j < len' becomes false and increment the value of variable j in every iteration

        (i) Check the condition 'a[i] == a[j]' if true print the element of array 'a[j]'

PHP Source Code

                                          <?php
$a = array(4, 9, 5, 6, 9, 3, 8, 8, 5);
$len = count($a);
echo "Elements in the array are:\n";
for ($i = 0; $i < $len; $i++) {
    echo "$a[$i] ";
}
echo "\nDuplicate elements in the array are:\n";
for ($i = 0; $i < $len; $i++) {
    for ($j = $i + 1; $j < $len; $j++) {
        if ($a[$i] == $a[$j])
            echo "$a[$j] ";
    }
}
?>
                                      

OUTPUT

Elements in the array are:
4 9 5 6 9 3 8 8 5
Duplicate elements in the array are:
9 5 8