How to use array_unique() Function In PHP

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
)

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

Similar Reads

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

Using Nested Loop

...