How can I remove duplicate values from an array in PHP?
$array = array("a" => "moon", "star", "b" => "moon", "star", "sky");
// Deleting the duplicate items
$result = array_unique($array);
print_r($result);
ref : Demo
Remove duplicate values from an associative array in PHP.
$arrDup = Array ('0' => 'aaa-aaa' , 'SKU' => 'aaa-aaa' , '1' => '12/1/1' , 'date' => '12/1/1' , '2' => '1.15' , 'cost' => '1.15' );
foreach($arrDup as $k => $v){
if(!( isset ($hold[$v])))
$hold[$v]=1;
else
unset($arrDup[$k]);
}
Array ( [0] => aaa-aaa [1] => 12/1/1 [2] => 1.15 )
Depending on the size of your array, I have found
$array = array_values( array_flip( array_flip( $array ) ) );
can be faster than array_unique.
If you concern in performance and have simple array, use:
array_keys(array_flip($array));
It's many times faster than array_unique.
We can create such type of array to use this last value will be updated into column or key value and we will get unique value from the array...
$array = array (1,3,4,2,1,7,4,9,7,5,9);
$data=array();
foreach($array as $value ){
$data[$value]= $value;
}
array_keys($data);
OR
array_values($data);
Here I've created a second empty array and used for
loop with the first array which is having duplicates. It will run as many time as the count of the first array. Then compared with the position of the array with the first array and matched that it has this item already or not by using in_array
. If not then it'll add that item to second array with array_push
.
$a = array(1,2,3,1,3,4,5);
$count = count($a);
$b = [];
for($i=0; $i<$count; $i++){
if(!in_array($a[$i], $b)){
array_push($b, $a[$i]);
}
}
print_r ($b);