PHP | Ds\Map filter() Function

The Ds\Map::filter() function is an inbuilt function in PHP which is used to create a new map using the filter function.

Syntax:

Ds\Map public Ds\Map::filter( $callback )

Parameters: It contains a single parameter $callback which is an optional parameter and it returns True if the value should be included, False otherwise.



Return value: This function returns a new map containing all the pairs 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\Map::filter() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to illustrate the filter() 
// function of Ds\map 
  
// Creating a Map 
$map = new \Ds\Map([
    1 => "Welcome",
    2 => "to",
    3 => "Geeks",  
    4 => "for",
    5 => "Geeks"]);
              
  
// Display new sequence using filter function 
var_dump($map->filter(function($key, $val) { 
    return $key % 3 == 0; 
})); 
  
?> 

chevron_right


Output:

object(Ds\Map)#3 (1) {
  [0]=>
  object(Ds\Pair)#2 (2) {
    ["key"]=>
    int(3)
    ["value"]=>
    string(5) "Geeks"
  }
}

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to illustrate the filter() 
// function of Ds\map 
  
// Creating a Map 
$map = new \Ds\Map([
        1 => 10, 
        2 => 20,
        3 => 30, 
        4 => 40,
        5 => 50]); 
              
// Display new sequence using filter function 
var_dump($map->filter(function($key, $val) { 
    return $val % 20 == 0; 
})); 
  
?> 

chevron_right


Output:

object(Ds\Map)#3 (2) {
  [0]=>
  object(Ds\Pair)#2 (2) {
    ["key"]=>
    int(2)
    ["value"]=>
    int(20)
  }
  [1]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    int(4)
    ["value"]=>
    int(40)
  }
}

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.