Check and Remove Duplicate Values from PHP Array

Jun 17th, 2007

I want to check whether my array holds duplicate entry and if it holds duplicate values then remove those duplicate value.

This code will directly remove the duplicate value from an Array.
1. Remove duplicate values from an array

<?php
$arrUnique = array_unique ($array1);
?>

This array_unique function work in this manner-
(String)element1 = (string)element2;
String representation of each value will be checked.

2. Check whether an array holds duplicate values

<?php
if (count(array_unique($arr3)) < count($arr3))
    echo 'Duplicate entry in array';
else
    echo 'No Duplicate values in array';
?>

So, after combining both codes, I can check and be assured that I have unique values in my array.

Related:

 

 

Possibly Related posts:

  1. Mahesh Dada
    May 4th, 2009 at 00:53 | #1

    hi thank you i get proper array but how i also change the key of my array
    ex. $arr=array(0=>2, 1=>2, 2=>4, 3=>4);
    $arr=array_unique($arr);

    o/p:
    array(0=>2, 3=>4);

    here i want
    array(0=>2, 1=>4);

  2. satyakaran
    May 4th, 2009 at 04:56 | #2

    Try with print_r(array_values(array_unique($arr)));

  3. rupesh
    June 16th, 2009 at 06:55 | #3

    hi satya prakash
    It was nice to read ur code for checking duplicate values in array.

    Thanks
    rupesh
    PHP developer
    Gurgaon, India

Comments are closed.