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

public function set(
  Tk $key,
  Tv $value,
): Map<Tk, Tv>;

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.


  • Tk $key
  • Tv $value



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

$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)');