Home > Backend Development > PHP Tutorial > How Can I Find the Unique Elements in Two Arrays Using PHP?

How Can I Find the Unique Elements in Two Arrays Using PHP?

Barbara Streisand
Release: 2024-12-12 10:47:11
Original
648 people have browsed it

How Can I Find the Unique Elements in Two Arrays Using PHP?

Identifying Non-Overlapping Elements in Two Arrays

In this programming scenario, you have two flat arrays:

$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

Your objective is to determine the values that appear exclusively in one of these arrays. In other words, you want to find the elements that are not shared between the two arrays.

Solution Using array_diff()

To find the non-overlapping elements, you can utilize the array_diff() function in PHP. This function takes two arrays as input and returns an array containing the values that exist in the first array but not in the second.

To get the difference between $array1 and $array2, you can use the following code:

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

This will give you an array containing the values that are unique to $array1. Similarly, you can find the values exclusive to $array2 using:

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

Combining the Differences

The array_diff() function only finds values that exist in one array but not the other. To obtain a comprehensive list of values that occur in only one of the arrays, you need to merge the two difference arrays.

This can be achieved with the following code:

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

The resulting $fullDiff array will contain all the non-overlapping elements from both $array1 and $array2.

The above is the detailed content of How Can I Find the Unique Elements in Two 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