xxxxxxxxxx
// Input array with duplicate elements
$inputArray = array(1, 2, 2, 3, 4, 4, 5);
// Remove duplicate elements
$uniqueArray = array_unique($inputArray);
// Output the unique array
print_r($uniqueArray);
xxxxxxxxxx
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Array
(
[a] => green
[0] => red
[1] => blue
)
xxxxxxxxxx
$array = array(
array('group' => 'test', 'name' => 'Jane'),
array('group' => 'test', 'name' => 'John'),
array('group' => 'admin', 'name' => 'superadmin')
);
$unique_values_by_key = array_unique(array_column($array, 'group'));
xxxxxxxxxx
<?php
// Sample array with duplicate elements
$array = [1, 2, 3, 4, 2, 3, 5, 1];
// Remove duplicates by converting the array to a set and then back to an array
$uniqueArray = array_values(array_unique($array));
print_r($uniqueArray);
?>
xxxxxxxxxx
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
xxxxxxxxxx
<?php
// Syntax: array_unique(array $array, int $flags = SORT_STRING): array
// Desc: Removes duplicate values from an array
$arr = Array("red", "red", "green", "blue", "blue", "white");
echo "<pre>";
print_r($arr);
echo "</pre> <br><br>";
$arrUnique = array_unique($arr);
echo "<pre>";
print_r($arrUnique);
echo "</pre> <br><br>";
/* -------- output -----------
Array
(
[0] => red
[1] => red
[2] => green
[3] => blue
[4] => blue
[5] => white
)
Array
(
[0] => red
[2] => green
[3] => blue
[5] => white
)
*/
?>
xxxxxxxxxx
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
xxxxxxxxxx
<?php
function uniquAsoc($array,$key){
$resArray=[];
foreach($array as $val){
if(empty($resArray)){
array_push($resArray,$val);
}else{
$value=array_column($resArray,$key);
if(!in_array($val[$key],$value)){
array_push($resArray,$val);
}
}
}
return $resArray;
}
$array=[['phone'=>123,'id'=>1],['phone'=>748,'id'=>1],['phone'=>958,'id'=>3]];
print_r(uniquAsoc($array,'id'));
/*
Array
(
[0] => Array
(
[phone] => 123
[id] => 1
)
[1] => Array
(
[phone] => 958
[id] => 3
)
)
*/
?>
xxxxxxxxxx
$unique_array = [];
foreach($your_array as $element) {
$hash = $element[field-that-should-be-unique];
$unique_array[$hash] = $element;
}
$result = array_values($unique_array);