How to remove duplicate values from Array in PHP

We can use the PHP array method to remove duplicate values from the array in PHP. array methods are default PHP methods that are used to manipulate arrays. To remove duplicate data from an array we can use array_unique to remove duplicate data from the indexed array and array_unique method with map method to remove from an associative array.

Answers 2
  • Remove duplicate elements from indexed array in PHP

    $myArray = [11,34,56,78,34,78];
    $myArrayNew = array_unique($myArray);
    print_r($myArrayNew);
    
    0
    //Output
    Array ( [0] => 11 [1] => 34 [2] => 56 [3] => 78 )

    We can use the array_unique method to remove duplicate records from the array. In our case, we have two duplicate records 34 and 78. After using array_unique() method we get array elements with 11, 34, 56, and 78 so we can see that this array method removes duplicate records from indexed arrays.    

  • Remove duplicate elements of associative array in PHP

    $result = array(
       0=>array('a'=>1,'b'=>'Hello'),
       1=>array('a'=>1,'b'=>'john'),
       2=>array('a'=>1,'b'=>'john')
    );
    $unique = array_map("unserialize", array_unique(array_map("serialize", $result)));
    print_r($unique);
    
    0
    //Output
    Array ( [0] => Array ( [a] => 1 [b] => Hello ) [1] => Array ( [a] => 1 [b] => john ) )

    It removes array elements if both keys and values are the same in the associative array else it treats as a unique element if keys and values are different with compared to other elements

  • Back to code snippet queries related php