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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.