HH\Vector::filter

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

Description

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

Returns a Vector containing the values of the current Vector 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().

Parameters

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

Return Values

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

Examples

<?hh

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

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

// Create a Vector of colors that contain the letter 'l'
$l_colors = $colors->filter($color ==> strpos($color, 'l') !== false);
var_dump($l_colors);

// Create a Vector of colors that aren't listed in $primary_colors
$non_primary_colors = $colors->filter(
  $color ==> !$primary_colors->contains($color),
);
var_dump($non_primary_colors);
Output
object(HH\Vector)#4 (2) {
  [0]=>
  string(4) "blue"
  [1]=>
  string(6) "yellow"
}
object(HH\Vector)#6 (1) {
  [0]=>
  string(6) "yellow"
}