using array_unique() function In PHP
The array_unique() function in PHP removes duplicate values from an array by comparing the values and removing subsequent occurrences. It returns a new array with only unique values while preserving the original order of elements. This function is simple and efficient for deduplicating arrays in PHP applications.
Example 1: PHP program to remove duplicate values from the array.
<?php
// Input Array
$a = array(
"red",
"green",
"red",
"blue"
);
// Array after removing duplicates
print_r(array_unique($a));
?>
Output:
Array
(
[0] => red
[1] => green
[3] => blue
)
Example 2: PHP program to remove duplicate elements from an associative array.
<?php
// Input array
$arr = array(
"a" => "MH",
"b" => "JK",
"c" => "JK",
"d" => "OR"
);
// Array after removing duplicates
print_r(array_unique($arr));
?>
Output:
Array
(
[a] => MH
[b] => JK
[d] => OR
)
Example 3: This is another way of removing the duplicates from the array using the PHP in_array() method.
<?php
// This is the array in which values
// will be stored after removing
// the duplicates
$finalArray = array();
// Input array
$arr = array(
"a" => "MH",
"b" => "JK",
"c" => "JK",
"d" => "OR"
);
foreach ($arr as $key => $value)
{
// If the value is already not stored
// in the final array
if (!in_array($value, $finalArray)) $finalArray[$key] = $value;
}
// End foreach
print_r($finalArray);
?>
Output:
Array
(
[a] => MH
[b] => JK
[d] => OR
)
How to remove duplicate values from array using PHP ?
In this article, we will discuss how to remove duplicate elements from an array in PHP. We can get the unique elements by using array_unique() function. This function will remove the duplicate values from the array.
Syntax
array array_unique($array, $sort_flags);
Note: The keys of the array are preserved i.e. the keys of the not removed elements of the input array will be the same in the output array.