How to remove duplicate values from Array in PHP

Created at 24-May-2021 , By samar

How to remove duplicate values from Array in PHP

In this article, we will see how to solve "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.
  • Remove duplicate elements from indexed array in PHP

    $myArray = [11,34,56,78,34,78];
    $myArrayNew = array_unique($myArray);
    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(
    $unique = array_map("unserialize", array_unique(array_map("serialize", $result)));
    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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.