How to Remove Duplicate Values from an Array in PHP?

Problem:

You have an array which has duplicate values. You want to make the array unique deleting the duplicate values.

Solution:

Use array_unique() function. It removes duplicate values from the array and makes it a unique one.

The code:

<?php
$week_days = array("Monday", "Tuesday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Subday");
$week_days = array_unique($week_days);
foreach($week_days as $key => $value)
    echo "[$key] = $value" . "<br />";
?>

[wpdm_file id=33]

Output:

[0] = Monday
[1] = Tuesday
[3] = Wednesday
[4] = Thursday
[5] = Friday
[6] = Saturday

How it works:
The array $week_days has two “Tuesday”. array_unique() function removes second value and return the array.

Serialize Array Keys

If you look carefully in the output above, you’ll see that the resulting array has no index [2]. The duplicate value was in this key which was removed by the array_unique() function. That means, array_unique() function preserves elements’ keys after removing duplicate values.

If you want to index the keys serially, use array_values() function. See the following code-

<?php
$week_days = array("Monday", "Tuesday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Subday");
$week_days = array_values(array_unique($week_days));
foreach($week_days as $key => $value)
    echo "[$key] = $value" . "<br />";
?>

[wpdm_file id=34]

Output:

[0] = Monday
[1] = Tuesday
[2] = Wednesday
[3] = Thursday
[4] = Friday
[5] = Saturday
[6] = Subday