HH\Map::map

Returns a Map after an operation has been applied to each value in the current Map.

Description

public function map(
  callable $callback,
): Map<Tk,Tu>

Returns a Map after an operation has been applied to each value in the current Map.

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

The keys will remain unchanged from the current Map to the returned Map.

Parameters

  • callable $callback - The callback containing the operation to apply to the current Map values.

Return Values

  • Map<Tk,Tu> - a Map containing key/value pairs after a user-specified operation is applied.

Examples

In this example the Map's values are mapped to the same type (strings):

<?hh

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

$m = Map {
  'red' => '#ff0000',
  'green' => '#00ff00',
  'blue' => '#0000ff',
  'yellow' => '#ffff00',
};

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

$css_colors = $capitalized->map($hex_code ==> "color: {$hex_code};");
var_dump($css_colors);
Output
object(HH\Map)#2 (4) {
  ["red"]=>
  string(7) "#FF0000"
  ["green"]=>
  string(7) "#00FF00"
  ["blue"]=>
  string(7) "#0000FF"
  ["yellow"]=>
  string(7) "#FFFF00"
}
object(HH\Map)#4 (4) {
  ["red"]=>
  string(15) "color: #FF0000;"
  ["green"]=>
  string(15) "color: #00FF00;"
  ["blue"]=>
  string(15) "color: #0000FF;"
  ["yellow"]=>
  string(15) "color: #FFFF00;"
}

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

<?hh

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

$m = Map {
  'red' => '#ff0000',
  'green' => '#00ff00',
  'blue' => '#0000ff',
  'yellow' => '#ffff00',
};

$decimal_codes = $m->map(fun('hexdec'));
var_dump($decimal_codes);
Output
object(HH\Map)#2 (4) {
  ["red"]=>
  int(16711680)
  ["green"]=>
  int(65280)
  ["blue"]=>
  int(255)
  ["yellow"]=>
  int(16776960)
}