HH\Map::filterWithKey

Returns a Map containing the values of the current Map that meet a supplied condition applied to its keys and values.

Description

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

Returns a Map containing the values of the current Map that meet a supplied condition applied to its keys and values.

Only keys and values that meet a certain criteria are affected by a call to filterWithKey(), while all values are affected by a call to mapWithKey().

The keys associated with the current Map remain unchanged in the returned Map; the keys will be used in the filtering process only.

Parameters

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

Return Values

  • Map<Tk,Tv> - a Map containing the values after a user-specified condition is applied to the keys and values of the current Map.

Examples

This example shows how filterWithKey allows you to use an element's value and corresponding key to determine whether to include it in the filtered Map.

<?hh

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

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

$primary_colors = Set {'red', 'green', 'blue'};

// Filter non-primary colors with a 100% red component
$non_primary_red_100 = $m->filterWithKey(
  ($color, $hex_code) ==> {
    $is_primary = $primary_colors->contains($color);
    $has_full_red_component = strpos($hex_code, '#ff') === 0;
    return $has_full_red_component && !$is_primary;
  },
);

var_dump($non_primary_red_100);
Output
object(HH\Map)#4 (1) {
  ["yellow"]=>
  string(7) "#ffff00"
}