Set Theory Union of arrays in PHP

后端 未结 10 859
独厮守ぢ
独厮守ぢ 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:58

    From the code in the PHP: Array Operators documentation:

     "apple", "b" => "banana");
    $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
    
    $c = $a + $b; // Union of $a and $b
    echo "Union of \$a and \$b: \n";
    var_dump($c);
    
    $c = $b + $a; // Union of $b and $a
    echo "Union of \$b and \$a: \n";
    var_dump($c);
    ?>
    

    When executed, this script will print the following:

    Union of $a and $b:
    array(3) {
      ["a"]=>
      string(5) "apple"
      ["b"]=>
      string(6) "banana"
      ["c"]=>
      string(6) "cherry"
    }
    Union of $b and $a:
    array(3) {
      ["a"]=>
      string(4) "pear"
      ["b"]=>
      string(10) "strawberry"
      ["c"]=>
      string(6) "cherry"
    }
    

提交回复
热议问题