PHP | Ds\Vector filter() Function

The Ds\Vector::filter() function is used to filter out the only elements which satisfy the condition defined in the callback function. After doing a filter on the vector, it will eliminate the elements which do not satisfy the condition mentioned in the function.

Syntax:

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

Parameters: This function accepts single parameter $callback which returns true if the element in the vector is to be included, else return false.



Return Value: This function returns the vector with all the elements which are filtered according to the callable function.

Below programs illustrate the Ds\Vector::filter() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create new vector element
$vector = new \Ds\Vector([1, 2, 3, 4, 5]);
  
echo "Original Vector elements\n";
  
// Display the vector element
var_dump($vector);
  
echo("\nElements greater than or equal to 4\n");
  
// Filter the vector element
var_dump($vector->filter(function($value) {
    return $value >= 4;
}));
  
?>

chevron_right


Output:

Original Vector elements
object(Ds\Vector)#1 (5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
}

Elements greater than or equal to 4
object(Ds\Vector)#3 (2) {
  [0]=>
  int(4)
  [1]=>
  int(5)
}

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create new vector element
$vector = new \Ds\Vector([1, 2, 3, 4, 5]);
  
echo "Original Vector elements\n";
  
// Display the vector element
var_dump($vector);
  
echo("\nOdd elements\n");
  
// Use filter() function to filter
// the vector element
var_dump($vector->filter(function($value) {
    return $value % 2 == 1;
}));
  
?>

chevron_right


Output:

Original Vector elements
object(Ds\Vector)#1 (5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
}

Odd elements
object(Ds\Vector)#3 (3) {
  [0]=>
  int(1)
  [1]=>
  int(3)
  [2]=>
  int(5)
}

Reference: http://php.net/manual/en/ds-vector.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.