Set Theory Union of arrays in PHP

后端 未结 10 863
独厮守ぢ
独厮守ぢ 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条回答
  •  猫巷女王i
    2020-12-14 06:56

    The OP did not specify whether the union is by value or by key and PHP has array_merge for merging values and + for merging the keys. The results depends on whether the array is indexed or keyed and which array comes first.

    $a = ['a', 'b'];
    $b = ['b', 'c'];
    
    $c = ['a' => 'A',  'b' => 'B'];
    ‌‌$d = ['a' => 'AA', 'c' => 'C'];
    

    Indexed array

    See array_merge

    By value using array_merge

    ‌‌array_merge($a, $b); // [‌0 => 'a', 1 => 'b', 2 => 'b', 3 => 'c']
    ‌‌array_merge($b, $a); // ‌[0 => 'b', 1 => 'c', 2 => 'a', 3 => 'b']
    

    merge by key using + operator

    See + operator

    ‌‌$a + $b; ‌// [0 => 'a', 1 => 'b']
    $b + $a; // [0 => 'b', 1 => 'c']
    

    Keyed array

    By value using array_merge

    ‌array_merge($c, $d); // ‌['a' => 'AA', 'b' => 'B', 'c' => 'C']
    array_merge($d, $c); // ['a' => 'A',  'c' => 'C', 'b' => 'B']
    

    merge by key using + operator

    $c + $d; // [‌'a' => 'A',  'b' => 'B', 'c' => 'C']
    ‌‌$d + $c; // ‌['a' => 'AA', 'c' => 'C', 'b' => 'B']
    

提交回复
热议问题