Saturday, June 13, 2026
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
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS