How to make an array unique PHP

Learn how to make an array unique in PHP with an example: use array_unique() to remove duplicate values from an array.

How to Make an Array Unique in PHP

In PHP, there are several ways to make an array unique, but the simplest and most efficient is to use the array_unique() function. This function takes an array as an argument and returns a new array containing only the unique values of the original array. Here is an example of how to use this function:


$originalArray = array(1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9, 10);
$uniqueArray = array_unique($originalArray);

print_r($uniqueArray);

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

The array_unique() function removes all duplicate values from the original array and returns the unique values as a new array. In the example above, the output is an array with only the unique values from the original array. Note that the order of the values in the new array may be different from the order in the original array.

There are other ways to make an array unique in PHP such as using the array_keys() function, sorting the array, or using a foreach loop. However, the array_unique() function is the simplest and most efficient way to make an array unique.

Answers (0)