$old_array=array("Mango","Banana","Orange","Banana");
$new_array=array_unique($old_array);
Now our $new_array will contain values ("Mango","Banana","Orange")
$old_array=array("Mango","Banana","Orange","Banana");
if(count($old_array) != count(array_unique($old_array))){
echo " Not Unique, there are duplicate elements ";
}else{
echo " No duplicate elements ";
}
The output is here
Not Unique, there are duplicate elements
$old_array=array("Mango","Banana","Orange","Banana");
$new_array=array_unique($old_array);
// What is not common in both arrays ( keys also considered ) ///
$duplicate=array_diff_assoc($old_array,$new_array);
while (list ($key, $val) = each ($duplicate)) {
echo "$key -> $val <br>";
}
Output
3 -> Banana
The array_unique() function removes duplicate values but resets the keys by default. To preserve the keys, use the second parameter:
$arr = ["a" => "apple", "b" => "banana", "c" => "apple"];
$new_array = array_unique($arr, SORT_REGULAR);
print_r($new_array);
// Output: Array ( [a] => apple [b] => banana )
Using array_unique() in multidimensional arrays can be tricky. Here's how to remove duplicate sub-arrays:
$arr = [
['name' => 'John', 'age' => 25],
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30]
];
$new_array = array_map('unserialize', array_unique(array_map('serialize', $arr)));
print_r($new_array);
Output
Array ( [0] => Array ( [name] => John [age] => 25 ) [2] => Array ( [name] => Jane [age] => 30 ) )
In some cases, you may want to ensure uniqueness across multiple fields in an array of associative arrays.
$people = [
['name' => 'Alice', 'email' => 'alice@example.com'],
['name' => 'Bob', 'email' => 'bob@example.com'],
['name' => 'Alice', 'email' => 'alice@example.com']
];
$unique_people = array_map('unserialize', array_unique(array_map('serialize', $people)));
print_r($unique_people);
Array ( [0] => Array ( [name] => Alice [email] => alice@example.com ) [1] => Array ( [name] => Bob [email] => bob@example.com ) )
When working with large arrays, removing duplicates can be resource-intensive. Consider combining *array_flip()* with array_keys() for faster execution:
$arr = array_fill(0, 100000, 'test');
$unique = array_keys(array_flip($arr));
print_r($unique);