Set Theory Union of arrays in PHP

后端 未结 10 792
独厮守ぢ
独厮守ぢ 2020-12-14 06:14

There are 3 operations with sets in mathematics: intersection, difference and union (unification). In PHP we can do this operations with arrays:

  • intersection:
相关标签:
10条回答
  • 2020-12-14 06:43

    Use array_unique and array_merge together.

    0 讨论(0)
  • 2020-12-14 06:45

    array_unique( array_merge( ... ) )

    0 讨论(0)
  • 2020-12-14 06:46

    Adrien's answer won't necessary produce a sequentially numbered array from two sequentially numbered arrays - here are some options that will:

    array_values(array_unique(array_merge($array1, $array2)));
    

    (Adrien's answer with renumbering the keys afterward)

    array_keys(array_flip($array1)+array_flip($array2))
    

    (Put the values in the keys, and use the array union operator)

    array_merge($array1, array_diff($array2, $array1))
    

    (Remove the shared values from the second array before merging)

    Benchmark results (for merging two arrays of length 1000 a thousand times on my system):

    • Unique (Adrien's version): 2.862163066864 seconds
    • Values_Unique: 3.12 seconds
    • Keys_Flip: 2.34 seconds
    • Merge_Diff: 2.64 seconds

    Same test, but with the two arrays being very similar (at least 80% duplicate):

    • Unique (Adrien's version): 2.92 seconds
    • Values_Unique: 3.15 seconds
    • Keys_Flip: 1.84 seconds
    • Merge_Diff: 2.36 seconds

    It seems using the array union operator to do the actual union is the fastest method. Note however that array_flip is only safe if the array's values are all strings or all integers; if you have to produce the union of an array of objects, I recommend the version with array_merge and array_diff.

    0 讨论(0)
  • 2020-12-14 06:48

    use "+" operator to do so. See the link Array Operators

    0 讨论(0)
  • 2020-12-14 06:50

    Try array_merge:

    array_unique(array_merge($array1, $array2));
    

    PHP Manual

    0 讨论(0)
  • 2020-12-14 06:50
    $result = array_merge_recursive($first, $second);
    

    can be useful when you have arrays with arrays inside.

    0 讨论(0)
提交回复
热议问题