HH\Map::set

Stores a value into the current Map with the specified key, overwriting the previous value associated with the key.

Description

public function set(
  Tk $k,
  Tv $v,
): Map<Tk,Tv>

Stores a value into the current Map with the specified key, overwriting the previous value associated with the key.

This method is equivalent to Map::add(). If the key to set does not exist, it is created. This is inconsistent with, for example, Vector::set() where if the key is not found, an exception is thrown.

$map->set($k,$v) is equivalent to $map[$k] = $v (except that set() returns the current Map).

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

Parameters

  • Tk $k - The key to which we will set the value.
  • Tv $v - The value to set.

Return Values

  • Map<Tk,Tv> - A shallow copy of the current Map with the updated the value set. The current Map is also updated.

Examples

Since Map::set() returns a shallow copy of $m itself, you can chain a bunch of set() calls together.

<?hh

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

$m = Map {
  'red' => '#ff0000',
  'green' => '#00ff00',
  'blue' => '#0000ff',
  'yellow' => '#ffff00',
};

// Set the value at key 'red'
$m->set('red', 'rgb(255, 0, 0)');

// Set the values at keys 'green' and 'blue'
$m->set('green', 'rgb(0, 255, 0)')
  ->set('blue', 'rgb(0, 0, 255)');

var_dump($m);
Output
object(HH\Map)#1 (4) {
  ["red"]=>
  string(14) "rgb(255, 0, 0)"
  ["green"]=>
  string(14) "rgb(0, 255, 0)"
  ["blue"]=>
  string(14) "rgb(0, 0, 255)"
  ["yellow"]=>
  string(7) "#ffff00"
}