How to Print Unique Elements an Given Array in PHP?
Last Updated :
24 Oct, 2023
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:
Using array_unique() Function
The array_unique() function is used to remove the duplicate values from an array. If there are multiple elements in the array with same values then the first appearing element will be kept and all other occurrences of this element will be removed from the array.
Syntax:
array array_unique($array , $sort_flags)
Example:
PHP
<?php
$array = [1, 1, 3, 3, 3, 4, 4, 5, 7];
$printUniqueElements = array_unique ( $array );
print_r( $printUniqueElements );
?>
|
Output
Array
(
[0] => 1
[2] => 3
[5] => 4
[7] => 5
[8] => 7
)
Using Nested Loop
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 ] , " " ;
}
}
$arr = [12, 10, 9, 45, 2, 10, 10, 45];
$len = sizeof( $arr );
printUniqueElements( $arr , $len );
?>
|
Share your thoughts in the comments
Please Login to comment...