How to convert array to unique list in PHP

WBOY
Release: 2024-04-28 10:09:02
Original
781 people have browsed it

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.

在 PHP 中将数组转换为不重复列表的方法

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);
Copy after login

Practical case

Consider an array that saves the product ID in the order:

$orderIds = [100, 101, 102, 100, 103];
Copy after login

Use the array_unique() function, We can filter duplicate order IDs:

$uniqueOrderIds = array_unique($orderIds);
var_dump($uniqueOrderIds);
Copy after login

Output:

array(5) {
  [0]=>
  int(100)
  [1]=>
  int(101)
  [2]=>
  int(102)
  [3]=>
  int(103)
}
Copy after login

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));
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template