PHP | Ds\Set filter() Function

The Ds\Set::filter() function is an inbuilt function in PHP which is used to create new set using filter function.
Syntax:
Ds\Set public Ds\Set::filter( $callback )
Parameters: This function accepts single parameter $callback which is optional and it returns True if the value should be included, False otherwise.
Return value: This function returns a new set containing all the values for which either the callback returned True or all values that convert to True if a callback was not provided.
Below programs illustrate the Ds\Set::filter() function in PHP:
Program 1:
<?php // Create new set $set = new \Ds\Set([10, 20, 30, 40, 50]); // Display new set using filter function var_dump($set->filter(function($val) { return $val % 4 == 0; })); ?> |
Output:
object(Ds\Set)#3 (2) {
[0]=>
int(20)
[1]=>
int(40)
}
Program 2:
<?php // Create new set $set = new \Ds\Set([2, 5, 4, 8, 3, 9]); // Display new set using filter function var_dump($set->filter(function($val) { return $val; })); ?> |
Output:
object(Ds\Set)#3 (6) {
[0]=>
int(2)
[1]=>
int(5)
[2]=>
int(4)
[3]=>
int(8)
[4]=>
int(3)
[5]=>
int(9)
}


