In php, to remove duplicates from an array, the easiest way is to use the array_unique() function to get the unique values and then use array_values() to reindex the array.

$example = array(1,2,4,7,5,4,1,2,3,3,3,4,4,5,5,5,6);

print_r(array_values(array_unique($example)));

//Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 7
    [4] => 5
    [5] => 3
    [6] => 6
)

You can also use array_flip() twice and remove duplicates since an array cannot have duplicate keys.

$example = array(1,2,4,7,5,4,1,2,3,3,3,4,4,5,5,5,6);

print_r(array_values(array_flip(array_flip($example))));

//Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 7
    [4] => 5
    [5] => 3
    [6] => 6
)

When working with arrays and collections of data in php, it is useful to be able to easily change and manipulate our data structures easily.

One such operation is to be able to get the unique values from an array and remove all duplicate items.

We can easily remove duplicates from a php array and get the unique values with the array_unique() function.

Below is how to use the array_unique() function to remove duplicates from an array. After using array_unique(), we can use array_values() to reindex the array.

$example = array(1,2,4,7,5,4,1,2,3,3,3,4,4,5,5,5,6);

print_r(array_values(array_unique($example)));

//Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 7
    [4] => 5
    [5] => 3
    [6] => 6
)

Using array_flip() to Remove Duplicates from Array in php

Another way you can remove all of the duplicates from a php array is with the array_flip() function.

The array_flip() function flips an array’s keys and values.

We can take advantage of the fact that an array cannot have duplicate keys and call array_flip() twice.

Below is how to use the array_flip() function to remove duplicates from an array. After using array_flip() twice, we can use array_values() to reindex the array.

$example = array(1,2,4,7,5,4,1,2,3,3,3,4,4,5,5,5,6);

print_r(array_values(array_flip(array_flip($example))));

//Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 7
    [4] => 5
    [5] => 3
    [6] => 6
)

Hopefully this article has been useful for you to learn how to remove duplicates from arrays in php.

Categorized in:

PHP,

Last Update: February 26, 2024