Removing Duplicate Values from Arrays in PHP
Eliminating duplicate values from arrays is a common task in PHP. Here are two effective methods to achieve this:
1. Using array_unique()
The array_unique() function returns a new array with duplicate values removed. It preserves key-value pairs, retains the first equal element, and does not work on multidimensional arrays.
$array = [1, 2, 2, 3]; $array = array_unique($array); // Array becomes (1, 2, 3)
2. Using array_values() with array_unique()
If you need the values re-indexed after removing duplicates, combine array_unique() with array_values():
$array = [1, 2, 2, 3]; $array = array_values(array_unique($array)); // Array becomes (1, 2, 3) re-indexed
Remember, array_unique() returns a new array, so make sure to assign it to a new variable or update the original variable reference.
The above is the detailed content of How Can I Remove Duplicate Values from an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!