search
HomeBackend DevelopmentPHP ProblemHow to find different values ​​in an array in php

In PHP programming, we often need to deal with arrays. During array processing, occasionally you need to find different values ​​in the array (that is, there are no repeated values). Below we will introduce several methods to help you find different values ​​in PHP arrays.

Method 1: Use the array_unique function

array_unique() function returns an array with duplicate values ​​removed. This function removes duplicate values ​​while retaining the array keys. The following is an example of using the array_unique() function:

    $arr = array(1, 2, 3, 4, 3, 5, 4, 6);
    $unique_arr = array_unique($arr);
    print_r($unique_arr);

Output:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [5] => 5
        [7] => 6
    )

In this example, we use the array_unique() function to remove duplicate values ​​​​in the $arr array and get A new array $unique_arr.

However, this method has a disadvantage, that is, it can only find different values ​​in an array. If you need to find out the different values ​​in multiple arrays, you need to write additional code.

Method 2: Use array_diff function

array_diff() function is used to calculate the difference set of arrays. It will return an array containing all the elements in the $arr1 array but not in the $arr2, $arr3, etc. arrays. The following is an example of using the array_diff() function:

    $arr1 = array(1, 2, 3, 4, 5);
    $arr2 = array(3, 4, 5, 6, 7);
    $diff_arr = array_diff($arr1, $arr2);
    print_r($diff_arr);

Output:

    Array
    (
        [0] => 1
        [1] => 2
    )

In this example, we use the array_diff() function to compare the difference between the $arr1 and $arr2 arrays. A new array $diff_arr is obtained, which contains elements in the $arr1 array but not in the $arr2 array.

You can use multiple arrays as parameters of the array_diff() function, for example:

    $arr1 = array(1, 2, 3, 4, 5);
    $arr2 = array(3, 4, 5, 6, 7);
    $arr3 = array(5, 6, 7, 8, 9);
    $diff_arr = array_diff($arr1, $arr2, $arr3);
    print_r($diff_arr);

Output:

    Array
    (
        [0] => 1
        [1] => 2
    )

In this example, we compare $arr1 and $arr2 , the difference set of the $arr3 array, a new array $diff_arr is obtained, which contains the elements in the $arr1 array but not in the $arr2 and $arr3 arrays.

Method 3: Use loop search

PHP’s foreach loop is a very practical loop method. We can use foreach loop and if conditional statement to find different values ​​in an array. The following is an example of using a foreach loop and if statement:

    $arr = array(1, 2, 3, 4, 3, 5, 4, 6);
    $result_arr = array();    // 新建一个空数组
    foreach ($arr as $value)
    {
        $count = 0;           // 新建一个变量来计数
        foreach ($arr as $sub_value)
        {
            if ($value == $sub_value)
            {
                $count++;
            }
        }
        if ($count == 1)      // 如果计数为1,说明是不同的值
        {
            $result_arr[] = $value;
        }
    }
    print_r($result_arr);

Output:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 5
        [3] => 6
    )

In this example, we create a new empty array $result_arr to store different values. Use a foreach loop to iterate over the $arr array, then use another foreach loop to count the number of occurrences of the element in the array, and if the number of occurrences is 1, add the element to the $result_arr array.

The disadvantage of this method is that if the array is larger, the efficiency may be lower.

Method 4: Use the array_count_values ​​function

array_count_values() function is used to count the number of occurrences of all values ​​in the array. It returns an array whose keys are the values ​​in the $arr array and whose values ​​are the number of times that value appears in the $arr array. The following is an example of using the array_count_values() function:

    $arr = array(1, 2, 3, 4, 3, 5, 4, 6);
    $count_arr = array_count_values($arr);
    $result_arr = array();
    foreach ($count_arr as $key => $value)
    {
        if ($value == 1)
        {
            $result_arr[] = $key;
        }
    }
    print_r($result_arr);

Output:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 5
        [3] => 6
    )

In this example, we use the array_count_values() function to count the number of occurrences of each element in the $arr array, and then Use a foreach loop to traverse the result array, find the element whose occurrence count is 1, and add it to the $result_arr array.

The advantage of this method is that the code is concise, but the disadvantage is that it may consume more memory.

Conclusion

The above introduces four methods to find different values ​​​​in an array in PHP. In actual development, we need to choose the most suitable method according to the actual situation. If the array is small, you can use method three or four; if you need to find different values ​​in multiple arrays, you can use method two; if you only need to find different values ​​in one array, you can use method one.

The above is the detailed content of How to find different values ​​in an 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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.