How to Remove Duplicate Values From Array in PHP using array_unique

In This PHP Tutorial We are going to learn how to remove duplicate values from array in PHP Programming Language.

The PHP built in function array_unique use to remove duplicate values from a PHP array. The PHP array_unique function takes an array as the input and returns a new array without duplicate values.

$result = array_unique($input);

Example : php remove duplicates from array

$colors=array('red','green','blue','red','blue');
$unique_colors=array_unique($colors);
print_r($colors_colors);
Array
(
[0] => red
[1] => green
[2] => blue
)

In This example, We have a PHP array called $colors and the $colors array contains duplicate  values(red and blue). Using php array_unique function, we remove the duplicate values and assign unique values to a new PHP array called $unique_colors.

Example 2

$array = array("a" => "green", "b" => "blue", "c" => "red","d" => "blue","e" => "black");
$array=array_unique($array);
print_r( $array);
Array
(
[a] => green
[b] => blue
[c] => red
[e] => black
)

In the above example, two array keys b and d contain the same value ‘blue’. So the PHP Array_unique function will remove the second key ‘d’ from the $array.

Summary - PHP remove Duplicates from Array

In PHP array_unique() function used to remove duplicate values from PHP arrays.