Home > Backend Development > PHP Tutorial > How to Find Unique Values in Two Flat Arrays Using PHP?

How to Find Unique Values in Two Flat Arrays Using PHP?

Barbara Streisand
Release: 2024-12-20 21:43:10
Original
1023 people have browsed it

How to Find Unique Values in Two Flat Arrays Using PHP?

Finding Unique Values in Two Flat Arrays

Given two flat arrays, determine the subset of values that occur exclusively in one of the arrays.

To find the unique values, we can leverage two PHP functions: array_diff() and array_merge().

$array1 = [64, 98, 112, 92, 92, 92];
$array2 = [3, 26, 38, 40, 44, 46, 48, 52, 64, 68, 70, 72, 102, 104, 106, 92, 94, 96, 98, 100, 108, 110, 112];
Copy after login

To find the values that are not present in both arrays, we can first calculate the difference between $array1 and $array2:

$diff1 = array_diff($array1, $array2);
Copy after login

This gives us the values unique to $array1. However, we also need to find the values unique to $array2:

$diff2 = array_diff($array2, $array1);
Copy after login

Finally, to combine both sets of unique values, we can use array_merge():

$fullDiff = array_merge($diff1, $diff2);
Copy after login

This line will output the following result:

Array (
    [0] => 3
    [1] => 26
    [2] => 38
    [3] => 40
    [4] => 44
    [5] => 46
    [6] => 48
    [7] => 52
    [8] => 68
    [9] => 70
    [10] => 72
    [11] => 102
    [12] => 104
    [13] => 106
    [14] => 108
    [15] => 110
)
Copy after login

This approach efficiently finds all the values that appear exclusively in one of the two flat arrays.

The above is the detailed content of How to Find Unique Values in Two Flat Arrays Using 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template