HH\Map::filter

Returns a Map containing the values of the current Map that meet a supplied condition.

Description

public function filter(
  (function(Tv):bool) $callback,
): Map<Tk,Tv>

Returns a Map containing the values of the current Map that meet a supplied condition.

Only values that meet a certain criteria are affected by a call to filter(), while all values are affected by a call to map().

The keys associated with the current Map remain unchanged in the returned Map.

Parameters

  • (function(Tv):bool) $callback - The callback containing the condition to apply to the current Map values.

Return Values

  • Map<Tk,Tv> - a Map containing the values after a user-specified condition is applied.

Examples

This example shows how filter returns a new Map containing only the values (and their corresponding keys) for which $callback returned true:

<?hh

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

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

// Filter $m for colors with a 100% red component
$red_100 = $m->filter($hex_code ==> strpos($hex_code, '#ff') === 0);
var_dump($red_100);
Output
object(HH\Map)#3 (2) {
  ["red"]=>
  string(7) "#ff0000"
  ["yellow"]=>
  string(7) "#ffff00"
}