Thursday, December 18, 2025
HomeLanguagesPHP | DsSet filter() Function

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)
}

Reference: https://www.php.net/manual/en/ds-set.filter.php

RELATED ARTICLES

Most Popular

Dominic
32455 POSTS0 COMMENTS
Milvus
108 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11958 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12036 POSTS0 COMMENTS
Shaida Kate Naidoo
6958 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6910 POSTS0 COMMENTS
Umr Jansen
6890 POSTS0 COMMENTS