How to use Nested Loop In PHP
We can print unique elements using nested loop. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on left side of it. If present, then ignores the element, else prints the element.
Example:
PHP
<?php function printUniqueElements( $arr , $len ) { for ( $i = 0; $i < $len ; $i ++) { $j = 0; for ( $j ; $j < $i ; $j ++) { if ( $arr [ $i ] == $arr [ $j ]) break ; } if ( $i == $j ) echo $arr [ $i ] , " " ; } } // Driver function $arr = [12, 10, 9, 45, 2, 10, 10, 45]; $len = sizeof( $arr ); printUniqueElements( $arr , $len ); ?> |
12 10 9 45 2
How to Print Unique Elements an Given Array in PHP?
Given an array, the task is to print all distinct elements of the given array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted.
Examples:
Input: arr[] = {5, 6, 5, 3, 6, 4, 3, 5}
Output: 5, 6, 3, 4
Input: arr[] = {1, 2, 3, 4, 5, 5, 4, 3, 3, 3}
Output: 1, 2, 3, 4, 5
There are two methods to solve this problem, these are:
Table of Content
- Using array_unique() Function
- Using Nested Loop