Home >Backend Development >PHP Problem >How to remove duplicate values ​​from array in php

How to remove duplicate values ​​from array in php

PHPz
PHPzOriginal
2023-04-20 09:07:45518browse

In PHP, sometimes we need to remove duplicate values ​​from an array to ensure that each element in the array is unique. In this article, we will introduce several methods to help you remove duplicate values ​​from arrays in PHP.

1. Use the array_unique() function

PHP has a built-in function array_unique() that can quickly delete duplicate values ​​in the array. This function returns a new array in which unique values ​​are retained only once.

The following is an example of using the array_unique() function:

$arr = array('a', 'b', 'c', 'b', 'd', 'a');
$arr = array_unique($arr);

print_r($arr);

Output result:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [4] => d
)

2. Use the array_diff() function

If you need to To remove duplicate values ​​from an array and also need to sort the results, you can use the array_diff() function. This function returns a new array that contains elements that are in the first array but not in other arrays, so deduplication can be achieved through this function.

The following is an example of using the array_diff() function:

$arr = array('a', 'b', 'c', 'b', 'd', 'a');
$arr = array_diff($arr, array(''));

print_r($arr);

Output result:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [4] => d
)

3. Use loops and in_array() function

In addition to the above In addition to the two functions, another common method is to use loops and the in_array() function. In this method, we iterate through the entire array and use the in_array() function to determine whether the current element has appeared. If it is, remove the element from the array.

The following is an example of using a loop and the in_array() function:

$arr = array('a', 'b', 'c', 'b', 'd', 'a');
$newArr = array(); // 用于存放不重复的元素

foreach ($arr as $value) {
    if (!in_array($value, $newArr)) {
        $newArr[] = $value;
    }
}

print_r($newArr);

Output results:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [4] => d
)

Summary

The above three methods can help you Remove duplicate values ​​from PHP arrays, which method you choose depends on your needs. If it is just simple deduplication, it is recommended to use the array_unique() function; if you need to sort, you can use the array_diff() function; if you need more flexible control, you can use the loop and in_array() function.

The above is the detailed content of How to remove duplicate values ​​from array in php. 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