HH\Vector::set

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

Description

public function set(
  int $k,
  Tv $v,
): Vector<Tv>

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

If the key is not present, an exception is thrown. If you want to add a value even if the key is not present, use add().

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

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

Parameters

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

Return Values

Examples

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

<?hh

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

$v = Vector {'red', 'green', 'blue', 'yellow'};

// Set the first element to 'RED'
$v->set(0, 'RED');

var_dump($v);

// Set the second and third elements using chaining
$v->set(1, 'GREEN')
  ->set(2, 'BLUE');

var_dump($v);
Output
object(HH\Vector)#1 (4) {
  [0]=>
  string(3) "RED"
  [1]=>
  string(5) "green"
  [2]=>
  string(4) "blue"
  [3]=>
  string(6) "yellow"
}
object(HH\Vector)#1 (4) {
  [0]=>
  string(3) "RED"
  [1]=>
  string(5) "GREEN"
  [2]=>
  string(4) "BLUE"
  [3]=>
  string(6) "yellow"
}