HH\Map::map
Returns a Map
after an operation has been applied to each value in the
current Map
public function map<Tu>(
(function(Tv): Tu) $callback,
): Map<Tk, Tu>;
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
.
Guide
Parameters
(function(Tv): Tu) $callback
- The callback containing the operation to apply to the currentMap
values.
Returns
Map<Tk, Tu>
- aMap
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 (string
s):
$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);
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 (int
s):
$m = Map {
'red' => '#ff0000',
'green' => '#00ff00',
'blue' => '#0000ff',
'yellow' => '#ffff00',
};
$decimal_codes = $m->map(fun('hexdec'));
var_dump($decimal_codes);
object(HH\Map)#2 (4) {
["red"]=>
int(16711680)
["green"]=>
int(65280)
["blue"]=>
int(255)
["yellow"]=>
int(16776960)
}