How to remove duplicate values from an array in PHP?

Use the array_unique() function. It removes the duplicate values and keeps only the first one. The keys of the remaining values are not changed.

<?php
$fruits = ["a" => "apple", "b" => "banana", "c" => "apple"];

print_r(array_unique($fruits));
?>

Output:

Tutorials Class - Output Window

Array
(
[a] => apple
[b] => banana
)

For a normal numeric array, you will see gaps in the keys after removing duplicates. Use array_values() to reindex it from 0.

<?php
$numbers = [1, 2, 2, 3, 1];

print_r(array_values(array_unique($numbers)));
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => 1
[1] => 2
[2] => 3
)

By default array_unique() compares values as strings, so "1" and 1 are treated as same value.


Learn more about the similar topics:
Tutorials
PHP Arrays
PHP Array Functions
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
What are the different PHP functions to sort an array?
PHP’s numerically indexed array begins with which position?
Which PHP function inserts an element to the end of an array?
Which PHP function can be used check if variable is an array?
How many types of arrays are available in PHP?
What is the use of array_chunk() function in PHP?
What is the use of in_array() function in PHP?