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
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS