Add a key/value pair to the end of the current Map.


public function add(
  Pair<Tk,Tv> $p,
): Map<Tk,Tv>

Add a key/value pair to the end of the current Map.

This method is equivalent to Map::set(). If the key in the Pair exists in the Map, the value associated with it is overwritten.

$map->add($p) is equivalent to both $map[$k] = $v and $map[] = Pair {$k, $v} (except that add() returns the Map).

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


  • Pair<Tk,Tv> $p - The key/value Pair to add to the current Map.

Return Values


The following example adds a single key-value pair to the Map $m and also adds multiple key-value pairs to $m through chaining. Since Map::add() returns a shallow copy of $m itself, you can chain a bunch of add() calls together, and that will add all those values to $m.


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

$m = Map {};

$m->add(Pair {'red', '#ff0000'});

// Map::add returns the Map so it can be chained
$m->add(Pair {'green', '#00ff00'})
  ->add(Pair {'blue', '#0000ff'})
  ->add(Pair {'yellow', '#ffff00'});
object(HH\Map)#1 (1) {
  string(7) "#ff0000"
object(HH\Map)#1 (4) {
  string(7) "#ff0000"
  string(7) "#00ff00"
  string(7) "#0000ff"
  string(7) "#ffff00"