php remove duplicates from array

Removing duplicates from an array in PHP

If you have a PHP array that contains duplicate values and you want to remove duplicates, there are several ways to do it. Here are some of the most common methods:

Using array_unique()

One of the simplest ways to remove duplicates from an array is to use the built-in PHP function array_unique(). This function takes an array as its parameter and returns a new array with all the duplicates removed.


        $arr = array(1, 2, 3, 4, 4, 5);
        $unique_arr = array_unique($arr);
        print_r($unique_arr);
    

This will output:


        Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [5] => 5
        )
    

As you can see, the duplicate value "4" has been removed.

Using a loop and in_array()

Another way to remove duplicates from an array is to use a loop and the in_array() function to check if a value already exists in the new array before adding it.


        $arr = array(1, 2, 3, 4, 4, 5);
        $unique_arr = array();
        foreach ($arr as $value) {
            if (!in_array($value, $unique_arr)) {
                $unique_arr[] = $value;
            }
        }
        print_r($unique_arr);
    

This will output the same result as using array_unique().

Using array_keys() and array_values()

A third method is to use the array_keys() and array_values() functions to remove duplicates from an associative array. This method preserves the keys of the original array.


        $arr = array("a" => 1, "b" => 2, "c" => 3, "d" => 2);
        $unique_keys = array_unique(array_keys($arr));
        $unique_arr = array_intersect_key($arr, $unique_keys);
        print_r($unique_arr);
    

This will output:


        Array
        (
            [a] => 1
            [b] => 2
            [c] => 3
        )
    

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe