Join my Laravel for REST API's course on Udemy 👀

Remove duplicate values from an array in PHP

July 13, 2022  ‐ 1 min read

To remove duplicate values from an array in PHP we can use the built-in array function array_unique().

This function requires the array to remove values from as a first argument. The second argument is optional and allows you to change how array elements are compared.

The function returns a new array, the original is not mutated by array_unique().

array_unique(array $array, int $flags = SORT_STRING): array
<?php

array_unique(['a', 'a', 'b', 'c']);
//=> ['a', 'b', 'c']

In case you are using Laravel collections, you might want to fall back on the unique() method that can be called on collections; see the docs.