How to Remove Duplicates From a PHP Array?

To remove duplicate values from a PHP array, you can simply use the array_unique() function, for example, like so:

$arr = [ 'foo', 'foo', 'bar', 'foo', 'baz', 'bar' ];
$uniqArr = array_unique($arr);

var_dump($uniqArr); // [0 => 'foo', 2 => 'bar', 4 => 'baz']

Please note that keys are preserved in the resulting array. When multiple elements compare equal to each other, then the key/value of the first element is retained. However, there are ways in which you can re-index the array (for example, using array_values() on the resulting array).

By default, the array_unique() function coerces all values into a string and then does a strict equality check (i.e. (string) $elem1 === (string) $elem2). This default behavior, however, can be changed by passing any one of the following flags as a second argument to array_unique():

SORT_STRING // (default) compare items as strings
SORT_REGULAR // compare items normally (i.e. without changing types)
SORT_NUMERIC // compare items numerically
SORT_LOCALE_STRING // compare items as strings based on the current locale

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.