Home > Backend Development > PHP Tutorial > 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
Release: 2024-04-29 08:33:01
Original
627 people have browsed it

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

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

Use array_values() and array_unique()

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

$unique_array = array_values(array_unique($array));
Copy after login

Practical case

Suppose we have an array containing duplicate values :

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

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

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

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']
Copy after login

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!

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