How to remove duplicate values from an array in PHP


Question

How can I remove duplicate values from an array in PHP?

1
140
7/12/2013 10:01:49 AM

Accepted Answer

Use array_unique().

Example:

$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
225
11/21/2008 2:39:33 AM

//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 )

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon