HH\Set::add

Add the value to the current Set.

Description

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

Add the value to the current Set.

$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 $v - The value to add to the current Set

Return Values

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.

<?hh

namespace Hack\UserDocumentation\API\Examples\Set\Add;

$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"
}