Removing Duplicate Values from Arrays in PHP
When dealing with arrays in PHP, it may be necessary to remove duplicate values to ensure data accuracy and efficiency.
Solution: array_unique()
For one-dimensional arrays, the native array_unique() function effectively removes duplicate values. It retains the key-value pair of the first instance of each unique element, preserving key order.
$array = [1, 2, 2, 3]; $array = array_unique($array); // Array is now [1, 2, 3]
Note: array_unique() is not suitable for multi-dimensional arrays.
Reindexing Values
If desired, you can use array_values() to reindex the array, starting from 0:
$array = array_unique($array); $array = array_values($array); // Array is now [1, 2, 3] with keys [0, 1, 2]
The above is the detailed content of How Can I Remove Duplicate Values from a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!