Home > Article > Backend Development > How to convert array to unique list in PHP
There are many ways to convert an array into a unique list in PHP: array_unique() function: associate the values in the array with keys, and select the first value corresponding to the key as a unique element. The array_flip() and array_keys() functions: first swap the array key values, and then return a new array containing all keys. Custom functions: For more complex cases, custom functions can be used to handle duplicate values in an array.
How to convert an array into a distinct list in PHP
When processing data, it is often necessary to convert an array into a distinct list Duplicate list. There are several ways to achieve this in PHP.
array_unique() function
array_unique()
function is the simplest way to convert an array into a unique list. It associates the values in the array with keys and selects the first value corresponding to the key as a unique element.
$array = [1, 2, 3, 1, 2, 4]; $uniqueArray = array_unique($array);
Practical case
Consider an array that saves the product ID in the order:
$orderIds = [100, 101, 102, 100, 103];
Use the array_unique()
function, We can filter duplicate order IDs:
$uniqueOrderIds = array_unique($orderIds); var_dump($uniqueOrderIds);
Output:
array(5) { [0]=> int(100) [1]=> int(101) [2]=> int(102) [3]=> int(103) }
array_flip() and array_keys() functions
Another way is to use array_flip()
and array_keys()
functions.
array_flip()
The function swaps the keys and values in the array. The array_keys()
function returns a new array containing all the keys in the array.
$array = [1, 2, 3, 1, 2, 4]; $uniqueArray = array_keys(array_flip($array));
This will produce the same results as the array_unique()
function.
Custom function
For more complex scenarios, you can also write your own custom function to handle duplicate values in the array.
function removeDuplicates($array) { $uniqueValues = []; foreach ($array as $value) { if (!in_array($value, $uniqueValues)) { $uniqueValues[] = $value; } } return $uniqueValues; }
The above is the detailed content of How to convert array to unique list in PHP. For more information, please follow other related articles on the PHP Chinese website!