HH\Vector::add

Appends a value to the end of the current Vector, assigning it the next available integer key.

Description

public function add(
  Tv $value,
): Vector<Tv>

Appends a value to the end of the current Vector, assigning it the next available integer key.

If you want to overwrite the value for an existing key, use set().

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

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

If $v is an object, future changes to the added element ARE reflected in $v, and vice versa.

Parameters

  • Tv $value

Return Values

Examples

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

<?hh

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

$v = Vector {};

$v->add('red');
var_dump($v);

// Vector::add returns the Vector so it can be chained
$v->add('green')
  ->add('blue')
  ->add('yellow');
var_dump($v);
Output
object(HH\Vector)#1 (1) {
  [0]=>
  string(3) "red"
}
object(HH\Vector)#1 (4) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
  [2]=>
  string(4) "blue"
  [3]=>
  string(6) "yellow"
}