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
// 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