php remove duplicate values from array code example
Example 1: php remove duplicates from array
<?php
$fruits_list = array('Orange', 'Apple', ' Banana', 'Cherry', ' Banana');
$result = array_unique($fruits_list);
print_r($result);
?>
Output:
Array ( [0] => Orange [1] => Apple [2] => Banana [3] => Cherry )
Example 2: array_unique
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Array
(
[a] => green
[0] => red
[1] => blue
)
Example 3: php remove duplicates from array
<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>
Output : Array ( [a] => red [b] => green )
Example 2:
$array = array(1, 2, 2, 3);
$array = array_unique($array);
Output : Array is now (1, 2, 3)
Example 4: javascript remove duplicates from array
function toUniqueArray(a){
var newArr = [];
for (var i = 0; i < a.length; i++) {
if (newArr.indexOf(a[i]) === -1) {
newArr.push(a[i]);
}
}
return newArr;
}
var colors = ["red","red","green","green","green"];
var colorsUnique=toUniqueArray(colors);
Example 5: how to remove duplicate values from a multidimensional array in php
We used this to de-duplicate results from a variety of overlapping queries.
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
Example 6: php check for duplicates in array
function has_dupes($array) {
$dupe_array = array();
foreach ($array as $val) {
if (++$dupe_array[$val] > 1) {
return true;
}
}
return false;
}