Home Backend Development PHP Problem How to remove duplicates from php array

How to remove duplicates from php array

Apr 23, 2023 am 10:05 AM

As a popular programming language, PHP provides convenient and efficient array operation methods, in which removing duplicate elements is a common requirement. This article will introduce several methods to implement PHP array deduplication and analyze their advantages and disadvantages in depth.

1. Use the array_unique function

The easiest way is to use PHP's built-in function array_unique(). This function will return a new array after deduplication, and it will not change the original array. The following is a sample code:

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

The output result is:

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

array_unique() function uses a hash table algorithm, which is highly efficient, but if the array element types are inconsistent, the result will be Unpredictable. Additionally, this function cannot handle keys for associative arrays, only numeric arrays, so in some cases other approaches need to be considered.

2. Use loops and in_array function

The second method is to use loops and in_array() function to manually remove duplicates. The in_array() function can check whether a value already exists in the array. The following is the sample code:

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

The output result is the same as the first method. This method has better flexibility than the array_unique() function and can handle the keys of associative arrays, but it requires manual writing of loop code, which is relatively troublesome and may be less efficient if there are many array elements.

3. Use the array_flip and array_keys functions

The third method is to use the array_flip() and array_keys() functions, which are used to exchange the keys and values ​​of the array respectively, and return all keys of the array of a new array. The purpose of using these two functions is to convert the original array into a numeric array, and then use the array_unique() function. The following is sample code:

$array = array('apple', 'banana', 'orange', 'banana', 'pear');
$new_array = array_unique(array_keys(array_flip($array)));
print_r($new_array);
Copy after login

The output results are the same as the first two methods. This method is more concise than the second method and does not change the original array, but it requires two additional operations, which may have an adverse impact on performance.

4. Use recursion and array_merge function

The last method is to use recursion and array_merge() function to deduplicate multi-dimensional arrays. This method can handle arrays of arbitrary dimensions. The following is a sample code:

$array = array('apple', 'banana', array('orange', 'banana'), 'pear');
$new_array = array();
function array_recursive_unique($array) {
    global $new_array;
    foreach ($array as $value) {
        if (is_array($value)) {
            array_recursive_unique($value);
        } else {
            if (!in_array($value, $new_array)) {
                $new_array[] = $value;
            }
        }
    }
}
array_recursive_unique($array);
print_r($new_array);
Copy after login

The output result is:

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

The advantage of this method is that it can handle arrays of arbitrary dimensions and does not require additional functions. But it requires manual writing of recursive code, which is relatively cumbersome and inefficient. For large arrays, the running time can be very long.

To sum up, this article introduces four common methods to achieve PHP array deduplication. Using the array_unique() function is the simplest and easiest to understand, but it cannot handle keys of associative arrays. You can handle any array type using loops and the in_array() function, but you need to write the loop code manually. Working with keys of associative arrays works well using the array_flip() and array_keys() functions, but requires additional operations. Arrays of arbitrary dimensions can be processed using recursion and the array_merge() function, but manually writing recursive code or using large-scale arrays may cause efficiency problems. The appropriate method should be selected based on actual needs and specific scenarios.

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the best practices for deduplication of PHP arrays What are the best practices for deduplication of PHP arrays Mar 03, 2025 pm 04:41 PM

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

Does PHP array deduplication need to be considered for performance losses? Does PHP array deduplication need to be considered for performance losses? Mar 03, 2025 pm 04:47 PM

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

Can PHP array deduplication take advantage of key name uniqueness? Can PHP array deduplication take advantage of key name uniqueness? Mar 03, 2025 pm 04:51 PM

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

How to Implement message queues (RabbitMQ, Redis) in PHP? How to Implement message queues (RabbitMQ, Redis) in PHP? Mar 10, 2025 pm 06:15 PM

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

What Are the Latest PHP Coding Standards and Best Practices? What Are the Latest PHP Coding Standards and Best Practices? Mar 10, 2025 pm 06:16 PM

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

What are the optimization techniques for deduplication of PHP arrays What are the optimization techniques for deduplication of PHP arrays Mar 03, 2025 pm 04:50 PM

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

How Do I Work with PHP Extensions and PECL? How Do I Work with PHP Extensions and PECL? Mar 10, 2025 pm 06:12 PM

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

How to Use Reflection to Analyze and Manipulate PHP Code? How to Use Reflection to Analyze and Manipulate PHP Code? Mar 10, 2025 pm 06:12 PM

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea

See all articles