如何在PHP中找到两个数组中的唯一元素?

时间:2021-02-02 12:12:58

For example, I have the two arrays in PHP:

例如,我在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?

什么是最好的方法来实现这一目标?

4 个解决方案

#1


6  

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

使用array_diff()从另一个数组中减去每个数组,如下所示:

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

#2


2  

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

http://php.net/array_diff

http://php.net/array_diff

#3


0  

You can use array_diff function to accomplish that problem. You have to use it twice to get results you are looking for.

您可以使用array_diff函数来完成该问题。您必须使用它两次才能获得所需的结果。

#4


0  

You can write your own function. As example:

你可以编写自己的函数。例如:

function uniq(array $arr){

$temp_arr = [];
for ($i = 0; $i < sizeof($arr); $i++) {
    if (in_array($arr[$i], $temp_arr)) {
            continue;
    }

    $temp_arr[] = $arr[$i];

    }

return $temp_arr;
}

print_r(uniq([1, 2, 3, 6, 6, 6, 7, 8, 7, 2, 2, 3, 6, 7, 0, 12, 123, 1, 4, 7, 66, 77]));

///Output: Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 6
[4] => 7
[5] => 8
[6] => 0
[7] => 12
[8] => 123
[9] => 4
[10] => 66
[11] => 77
)

#1


6  

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

使用array_diff()从另一个数组中减去每个数组,如下所示:

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

#2


2  

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

http://php.net/array_diff

http://php.net/array_diff

#3


0  

You can use array_diff function to accomplish that problem. You have to use it twice to get results you are looking for.

您可以使用array_diff函数来完成该问题。您必须使用它两次才能获得所需的结果。

#4


0  

You can write your own function. As example:

你可以编写自己的函数。例如:

function uniq(array $arr){

$temp_arr = [];
for ($i = 0; $i < sizeof($arr); $i++) {
    if (in_array($arr[$i], $temp_arr)) {
            continue;
    }

    $temp_arr[] = $arr[$i];

    }

return $temp_arr;
}

print_r(uniq([1, 2, 3, 6, 6, 6, 7, 8, 7, 2, 2, 3, 6, 7, 0, 12, 123, 1, 4, 7, 66, 77]));

///Output: Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 6
[4] => 7
[5] => 8
[6] => 0
[7] => 12
[8] => 123
[9] => 4
[10] => 66
[11] => 77
)