How to Remove Duplicate Value From Array in PHP?
In this article, i will share with you how to remove duplicate values from an array in PHP using the array_unique()
example.
here I will share many examples of how to remove duplicate values from an array in PHP.
Example - 1 :
<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
Example - 2 :
$unique=array("","A1","","A2","","A1","");
$duplicated=array();
foreach($unique as $k=>$v) {
if( ($kt=array_search($v,$unique))!==false and $k!=$kt )
{ unset($unique[$kt]); $duplicated[]=$v; }
}
sort($unique); // optional
sort($duplicated); // optional
Output :
array ( 0 => '', 1 => 'A1', 2 => 'A2', ) /* $unique */
array ( 0 => '', 1 => '', 2 => '', 3 => 'A1', ) /* $duplicated */
Example - 3 :
//Find duplicates
$arr = array(
'unique',
'duplicate',
'distinct',
'justone',
'three3',
'duplicate',
'three3',
'three3',
'onlyone'
);
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
// array( 5=>'duplicate', 6=>'three3' 7=>'three3' )
// count duplicates
array_count_values($dupes); // array( 'duplicate'=>1, 'three3'=>2 )
i hope it will help you.
Copyright 2023 HackTheStuff