PHP array_unique() Function

PHP array_unique() function is used to remove duplicate values from an array. If there are multiple elements in the array with the same values, then the first appearing element will be kept, and all other occurrences of this element will be removed from the array.

Important points to know:

  • The keys of array are preserved.
  • array_unique() is not intended to work on multidimensional arrays.

Syntax

array_unique($array, [sortingType])

Parameters

array(required): It is an input array.

sortingType(optional): Specifying how to compare the array element. The following are some soringType flags.

  1. SORT_REGULAR – Compare items usually (don’t change types)
  2. SORT_NUMERIC – Compare items numerically
  3. SORT_STRING(Default) – Compare items as strings
  4. SORT_LOCAL_STRING – Compare items as strings based on the current locale.

Return value

It returns an array that contains unique elements.

Visual RepresentationVisual Representation of PHP array_unique() Function

Example 1: How to Use array_unique() function

<?php

$singer = ["Drake","Justin","Selena","Drake","Rema"];

echo "Before apply unique: \n";

print_r($singer);

echo "After apply unique: \n";

print_r(array_unique($singer));

Output

Before apply unique: 
Array
(
 [0] => Drake
 [1] => Justin
 [2] => Selena
 [3] => Drake
 [4] => Rema
)
After apply unique: 
Array
(
 [0] => Drake
 [1] => Justin
 [2] => Selena
 [4] => Rema
)

The output contains unique elements “Drake”, “Justin”, “Selena”, and “Rema”.

You can see that the keys of the input array are preserved.

Example 2: Using Associative Array

<?php

$name = ["a" => "krunal", 
 "b" => "krunal",
 "c" => "ankit", 
 "d" => "Yuvi", 
 "e" => "rushabh"];
 
echo "Before apply unique: \n";

print_r($name);
 
$result = array_unique($name);

echo "After apply unique: \n";

print_r($result);

Output

Before apply unique: 
Array
(
 [a] => krunal
 [b] => krunal
 [c] => ankit
 [d] => Yuvi
 [e] => rushabh
)
After apply unique: 
Array
(
 [a] => krunal
 [c] => ankit
 [d] => Yuvi
 [e] => rushabh
)

That’s it.

1 thought on “PHP array_unique() Function”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.