How to remove duplicate arrays in php

PHPz
Release: 2023-04-18 14:00:13
Original
493 people have browsed it

In PHP development, sometimes we encounter situations where we need to remove duplicate elements from an array. Here are several methods to remove duplicate elements from an array:

1. Use the array_unique() function

array_unique() to remove duplicate elements from an array and return a new array without duplicate elements.

Sample code:

$arr = array('apple', 'banana', 'orange', 'apple');
print_r(array_unique($arr));
Copy after login

Output result:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)
Copy after login
Copy after login
Copy after login

2. Use foreach loop

Use foreach loop to traverse the array, and for each element, determine its Whether it already exists in the new array, if it does not exist, it will be added to the new array, if it exists, it will be ignored. This method is relatively simple, but may not be very performant for large arrays.

Sample code:

$arr = array('apple', 'banana', 'orange', 'apple');
$newArr = array();
foreach ($arr as $value) {
    if (!in_array($value, $newArr)) {
        $newArr[] = $value;
    }
}
print_r($newArr);
Copy after login

Output result:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)
Copy after login
Copy after login
Copy after login

3. Use the array_flip() and array_keys() functions

to reverse the keys and values ​​of the array Turn, remove duplicates and then reverse back. This method is applicable when the value of the array is a simple type (such as string, number, etc.), but not applicable when the value of the array is a complex type such as an object.

Sample code:

$arr = array('apple', 'banana', 'orange', 'apple');
$newArr = array_flip(array_keys(array_flip($arr)));
print_r($newArr);
Copy after login

Output result:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)
Copy after login
Copy after login
Copy after login

Summary

The above three methods can successfully remove duplicate elements in the array. Which method to use can be chosen according to the actual situation. If the performance requirements for the array are not high, you can use a foreach loop. If high performance is required, it is recommended to use array_unique() or use the array_flip() and array_keys() functions.

The above is the detailed content of How to remove duplicate arrays in php. For more information, please follow other related articles on the PHP Chinese website!

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