HH\Map::add

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

Description

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.

Parameters

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

Return Values

Examples

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.

<?hh

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

$m = Map {};

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

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