What is the Ds\Set union() function in PHP?

In PHP, the Ds\Set::union() function is used to find the union of two sets. The union of two sets is a set that contains all the elements that are present either in the first set or the second set.

Syntax

The Ds\Set::union() function can be declared as shown in the code snippet below:

Ds\Set public Ds\Set::union ( Ds\Set $set )

Parameter

The Ds\Set::union() takes the following parameter:

  • set: This is the second set that takes union with the first set.

Return value

The Ds\Set::union() function returns the union of the sets, that is, a set containing the elements that are present in the first or second set.

Code example

Let’s look at the code snippet given below, which demonstrates the use of the Ds\Set::union() function:

<?php
$set1 = new \Ds\Set([1, 2, 3, 4]);
$set2 = new \Ds\Set([3, 4, 5, 6]);
echo("Union of set1 and set2: \n");
print_r($set1->union($set2));
?>

Explanation

  • Line 3: We declare a set called set1.
  • Line 5: We declare a set called set2.
  • Line 9: We call the Ds\Set::union() function to find the union of set1 and set2.

Free Resources