HH\Vector::map

Returns a Vector containing the results of applying an operation to each value in the current Vector

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

map()'s result contains a value for every value in the current Vector; unlike filter(), where only values that meet a certain criterion are included in the resulting Vector.

Guide

Parameters

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

Returns

  • Vector<Tu> - A Vector containing the results of applying a user-specified operation to each value of the current Vector in turn.

Examples

In this example the Vector's elements are mapped to the same type (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):

$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)
}