Home  >  Article  >  Backend Development  >  Solve the problem of changing the order of elements after deduplication in PHP arrays

Solve the problem of changing the order of elements after deduplication in PHP arrays

WBOY
WBOYOriginal
2024-04-29 08:33:01528browse

PHP There are three solutions to the problem of changing the order of elements when deduplicating arrays: use array_intersect_key(), array_flip() and array() and array_values() and array_unique() to preserve the order of array elements.

解决 PHP 数组去重后元素顺序变化的问题

Solve the problem of changing the order of elements after deduplication in PHP arrays

Problem description

PHP array uses array_unique() After function deduplication, the order of elements may change. This may lead to unexpected results in some cases.

Solution

To preserve the order of array elements, you can use the following method:

Use array_intersect_key()

$array = ['a', 'b', 'c', 'a', 'd'];

$unique_array = array_intersect_key($array, array_unique($array));

Use array_flip() and array()

$array = ['a', 'b', 'c', 'a', 'd'];

$unique_array = array();
$seen_keys = array_flip($array);

foreach ($seen_keys as $key => $val) {
    $unique_array[$key] = $array[$key];
}

Use array_values() and array_unique()

$array = ['a', 'b', 'c', 'a', 'd'];

$unique_array = array_values(array_unique($array));

Practical case

Suppose we have an array containing duplicate values :

$array = ['red', 'green', 'blue', 'red', 'orange'];

Use array_unique() After deduplication, the order of elements changes:

$unique_array = array_unique($array); // ['green', 'blue', 'orange', 'red']

Use the method mentioned above to preserve the order of elements:

$unique_array_intersect = array_intersect_key($array, array_unique($array)); // ['red', 'green', 'blue', 'a']
$unique_array_flip = array();
$seen_keys = array_flip($array);
foreach ($seen_keys as $key => $val) {
    $unique_array_flip[$key] = $array[$key];
} // ['red', 'green', 'blue', 'a']
$unique_array_values = array_values(array_unique($array)); // ['red', 'green', 'blue', 'orange']

The above is the detailed content of Solve the problem of changing the order of elements after deduplication in PHP arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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