- PHP

How to remove duplicates in PHP array

The simplest way to keep only unique values in the array is to use the pre-built array_unique function. It will remove all duplicate values from the defined array.

$newArray = array_unique($array);

Example:

Remove all the duplicates from the array.

<?php

$pets = ['dog', 'turtle', 'dog', 'cat', 'bird', 'cat', 'cat'];

$uniquePets = array_unique($pets);

print_r($uniquePets);

?>

Output:

Array ( [0] => dog [1] => turtle [3] => cat [4] => bird )