How to use PHP for() Loop In PHP

First, we will declare and initialize an array, and use PHP sizeof() function to get the array size. Then we will use nested for() loop to compare the array elements, and if two elements are same, then print the value. If no value is repeated, then it will not print any value.

Syntax:

for ($i = 0; $i < $arr_length; $i++) {
for ($j = $i + 1; $j < $arr_length; $j++) {
// checking for duplicates
if ($array[$i] == $array[$j])
echo "$array[$j] ";
}
}

Example: This example uses nested for loop to get the unique elements from an array.

PHP
<?php 

// Declare an array with repeated elements 
$arr = array(2, 3, 5, 3, 5, 9); 

// Get the length of an array 
$length = sizeof($arr); 

// Using Nested for Loop to get the 
// repeated elements 
for ($i = 0; $i < $length; $i++) { 
    for ($j = $i + 1; $j < $length; $j++) { 
        if ($arr[$i] == $arr[$j]) 
            echo "$arr[$j] "; 
    } 
} 

?>

Output
3 5 

PHP Program to Find Duplicate Elements from an Array

Given an array containing some repeated elements, the task is to find the duplicate elements from the given array. If array elements are not repeated, then it returns an empty array.

Examples:

Input: arr = [1, 2, 3, 6, 3, 6, 1]
Output: [1, 3, 6]

Input: arr = [3, 5, 2, 5, 3, 9]
Output: [3, 5]

There are two methods to get the duplicate elements from an array, these are:

Table of Content

  • Using PHP array_diff_assoc() and array_unique() Functions
  • Using PHP for() Loop
  • Using array_count_values() and array_filter()
  • Using array_filter and array_keys

Similar Reads

Using PHP array_diff_assoc() and array_unique() Functions

The PHP array_diff_assoc() function is used to find the difference between one or more arrays. This function compares both the keys and values between one or more arrays and returns the difference between them....

Using PHP for() Loop

First, we will declare and initialize an array, and use PHP sizeof() function to get the array size. Then we will use nested for() loop to compare the array elements, and if two elements are same, then print the value. If no value is repeated, then it will not print any value....

Using array_count_values() and array_filter()

To find duplicate elements from an array in PHP using array_count_values() and array_filter(), first count the occurrences of each value. Then, filter the counts to include only those greater than one, and extract the corresponding keys as duplicates....

Using array_filter and array_keys

Using array_filter and array_keys to find duplicates involves filtering the array to keep only elements that appear more than once, then utilizing `array_keys` to count occurrences. The filtered elements are then deduplicated with `array_unique` to get the final list of duplicates....