What is the DS\Set filter() method in PHP?
The filter() method of the DS\Set class in PHP eliminates the values that fail to satisfy the condition defined in a provided callback function from a set.
The process is illustrated below.
Syntax
The prototype of the filter() method is shown below.
public Ds\Set::filter(callable $callback = ?): Ds\Set
Parameters
The filter() method accepts a single optional parameter: a callback function that defines the condition based on which values are eliminated from the set.
Return value
The filter() method returns a new set that contains all the values of the original set for which the callback function returns true.
If the callback function is not provided as a parameter, the filter() method only retains the values evaluated as true.
Note: You can check this link to learn how values are evaluated as
Booleanin PHP.
Code
The example below shows how the filter() method works in PHP.
<?php// initialize sets$firstSet = new \Ds\Set([1, 5, 8, 10, 15]);$secondSet = new \Ds\Set([0, 'abc', 10, true, false]);// filter out all values not divisible by 5$filterFirst = $firstSet->filter(function($value){return $value % 5 == 0;});// filter without callback$filterSecond = $secondSet->filter();// print filtered setsprint_r($filterFirst);print_r($filterSecond);?>
Output
The code above produces the following output.
Ds\Set Object
(
[0] => 5
[1] => 10
[2] => 15
)
Ds\Set Object
(
[0] => abc
[1] => 10
[2] => 1
)
Note: To run this program, you need to install Data Structures for PHP on your local machine.
Explanation
First, two sets are initialized: firstSet and secondSet.
The filter() method in line proceeds to filter out values from firstSet. The callback function provided to this filter() method returns true if a value is divisible by five. Therefore, the filter() method returns a new set that contains only the values of firstSet that are divisible by five.
The filter() method in line filters out values from secondSet. Since no callback function is provided to the filter() method, it eliminates all the values of secondSet that do not evaluate to true, i.e., 0 and false.