HH\Vector::map

Returns a Vector containing the values after an operation has been applied to each value in the current Vector.

Description

public function map(
  (function(Tv):Tu) $callback,
): Vector<Tu>

Returns a Vector containing the values after an operation has been applied to each value in the current Vector.

Every value in the current Vector is affected by a call to map(), unlike filter() where only values that meet a certain criteria are affected.

Parameters

  • (function(Tv):Tu) $callback - The callback containing the operation to apply to the Vector values.

Return Values

  • Vector<Tu> - a Vector containing the values after a user-specified operation is applied.

Examples

In this example the Vector's elements are mapped to the same type (strings):

<?hh

namespace Hack\UserDocumentation\API\Examples\Vector\Map\Strings;

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

$capitalized = $v->map(fun('strtoupper'));
var_dump($capitalized);

$shortened = $v->map($color ==> substr($color, 0, 3));
var_dump($shortened);
Output
object(HH\Vector)#2 (4) {
  [0]=>
  string(3) "RED"
  [1]=>
  string(5) "GREEN"
  [2]=>
  string(4) "BLUE"
  [3]=>
  string(6) "YELLOW"
}
object(HH\Vector)#4 (4) {
  [0]=>
  string(3) "red"
  [1]=>
  string(3) "gre"
  [2]=>
  string(3) "blu"
  [3]=>
  string(3) "yel"
}

In this example the Vector's elements are mapped to a different type (ints):

<?hh

namespace Hack\UserDocumentation\API\Examples\Vector\Map\Ints;

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

$lengths = $v->map(fun('strlen'));
var_dump($lengths);
Output
object(HH\Vector)#2 (4) {
  [0]=>
  int(3)
  [1]=>
  int(5)
  [2]=>
  int(4)
  [3]=>
  int(6)
}