Home  >  Article  >  Backend Development  >  How to remove duplicate elements from PHP array

How to remove duplicate elements from PHP array

PHPz
PHPzOriginal
2023-04-26 10:21:02531browse

In PHP development, array (Array) is an inevitable data type. It can store multiple values ​​​​or strings and perform corresponding operations. However, during the development process, we sometimes need to deduplicate the array, that is, remove duplicate elements. This article will introduce how to remove duplicate elements from PHP arrays.

Method 1: Use array_unique() function

PHP’s built-in function array_unique() can easily remove duplicate elements from an array. This function keeps the first occurrence of the element and removes subsequent duplicate elements.

Syntax: array_unique(array);

Sample code:

$names = array("Tom", "Jerry", "Tom", "Peter", "Jerry");
print_r(array_unique($names));

Output result:

Array ( [0] => Tom [1] => Jerry [3] => Peter )

Method 2: Use loop traversal

Another method is to use a loop to traverse the array. Whenever a new element is encountered, determine whether the element already exists in the new array. If it does not exist, add it to the new array.

Sample code:

$names = array("Tom", "Jerry", "Tom", "Peter", "Jerry");
$new_names = array();

foreach ($names as $name) {
    if (!in_array($name, $new_names)) {
        $new_names[] = $name;
    }
}

print_r($new_names);

Output result:

Array ( [0] => Tom [1] => Jerry [3] => Peter )

Method 3: Use the array_flip() function

array_flip() function can convert the keys in the array and values ​​are interchanged, therefore, duplicate elements in the array can be removed through the array_flip() and array_keys() functions.

Sample code:

$names = array("Tom", "Jerry", "Tom", "Peter", "Jerry");
$new_names = array_flip(array_keys(array_flip($names)));

print_r($new_names);

Output result:

Array ( [0] => Tom [1] => Jerry [3] => Peter )

The above three methods can effectively remove duplicate elements in PHP arrays. Which method to use depends on the actual situation.

The above is the detailed content of How to remove duplicate elements from PHP array. 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