Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Removing duplicate elements from an array in PHP
In PHP, there are several methods to remove duplicate elements from an array. The most common approaches include using array_unique(), array_flip(), or array_keys() with array_count_values().
Using array_flip()
The array_flip() function reverses keys and values. When flipped twice, duplicate values are automatically removed since array keys must be unique −
<?php $my_arr = array(45, 65, 67, 99, 81, 90, 99, 45, 68); echo "The original array contains <br>"; print_r($my_arr); $my_arr = array_flip($my_arr); $my_arr = array_flip($my_arr); $my_arr = array_values($my_arr); echo "\nThe array after removing duplicate elements is <br>"; print_r($my_arr); ?>
The original array contains Array ( [0] => 45 [1] => 65 [2] => 67 [3] => 99 [4] => 81 [5] => 90 [6] => 99 [7] => 45 [8] => 68 ) The array after removing duplicate elements is Array ( [0] => 45 [1] => 65 [2] => 67 [3] => 99 [4] => 81 [5] => 90 [6] => 68 )
Using array_unique()
The simplest method is using PHP's built-in array_unique() function −
<?php $my_arr = array(45, 65, 67, 99, 81, 90, 99, 45, 68); echo "Original array:<br>"; print_r($my_arr); $unique_arr = array_unique($my_arr); $unique_arr = array_values($unique_arr); // Re-index array echo "\nAfter removing duplicates:<br>"; print_r($unique_arr); ?>
Original array: Array ( [0] => 45 [1] => 65 [2] => 67 [3] => 99 [4] => 81 [5] => 90 [6] => 99 [7] => 45 [8] => 68 ) After removing duplicates: Array ( [0] => 45 [1] => 65 [2] => 67 [3] => 99 [4] => 81 [5] => 90 [6] => 68 )
Comparison
| Method | Performance | Complexity |
|---|---|---|
array_unique() |
Good | Simple |
array_flip() |
Faster | Moderate |
Conclusion
Use array_unique() for simplicity or array_flip() for better performance with large arrays. Both methods effectively remove duplicates while preserving the first occurrence of each unique value.
Advertisements
