HH\Set::add

Add the value to the current Set

public function add(
  Tv $val,
): Set<Tv>;

$set->add($v) is semantically equivalent to $set[] = $v (except that add() returns the Set).

Future changes made to the current Set ARE reflected in the returned Set, and vice-versa.

Parameters

  • Tv $val

Returns

Examples

The following example adds a single value to the Set $s and also adds multiple values to $s through chaining. Since Set::add() returns a shallow copy of $s itself, you can chain a bunch of add() calls together, and that will add all those values to $s. Notice that adding a value that already exists in the Set has no effect.

$s = Set {};

$s->add('red');
var_dump($s);

// Set::add returns the Set so it can be chained
$s->add('green')
  ->add('blue')
  ->add('yellow');
var_dump($s);

// Adding an element that already exists in the Set has no effect
$s->add('green')
  ->add('blue')
  ->add('yellow');
var_dump($s);
Output
object(HH\Set)#1 (1) {
  string(3) "red"
}
object(HH\Set)#1 (4) {
  string(3) "red"
  string(5) "green"
  string(4) "blue"
  string(6) "yellow"
}
object(HH\Set)#1 (4) {
  string(3) "red"
  string(5) "green"
  string(4) "blue"
  string(6) "yellow"
}