Skip to content
the poor coder

php remove duplicates from array

Poor Man
Published
Reading time
1 min read
On this page

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.

Text

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

This will output:

Text

        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.

Text

        $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.

Text

        $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:

Text

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

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC