Check and Remove Duplicate Values from PHP Array

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:

  • # 1 - by Mahesh Dada

    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 - by Mahesh Dada

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

  • # 3 - by satyakaran

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

  • # 4 - by satyakaran

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

  • # 5 - by rupesh

    hi satya prakashIt was nice to read ur code for checking duplicate values in array.Thanksrupesh PHP developerGurgaon, India

Comment pages
1 2 219
Comments are open for an year period. Please, write here on Facebook page.