GSto GSto - 1 month ago 4
PHP Question

How to find the unique elements in two arrays in PHP?

For example, I have the two arrays in PHP:

$arr1 = array(1,3,5);
$arr2 = array(1,4,6);


I'd like to create two new arrays, with each containing the elements that are unique to each array. So I would like to get the following two arrays as output:

$arr1_uniques = array(3,5);
$arr2_uniques = array(4,6);


what would be the best way to accomplish this?

Answer

Use array_diff() to subtract each array from the other, like so:

$arr1_uniques = array_diff($arr1, $arr2);
$arr2_uniques = array_diff($arr2, $arr1);
Comments