PHP - Ds Sequence::filter() Function



The PHP Ds\Sequence::filter() function is used to create a new sequence by applying a callable (callback function) that determines which values should be included.

The callable should return "true", if a value should be included in the new sequence. If no callback is provided, the function will include all values that are converted to true and exclude values that are converted to "false".

Syntax

Following is the syntax of the PHP Ds\Sequence::filter() function −

public abstract Ds\Sequence Ds\Sequence::filter([ callable $callback ] )

Parameters

Following is the parameter of this function −

  • callback − An optional callable function returns 'true' if value should be included or 'false' otherwise.

Following is the syntax of the callback function −

callback(mixed $value): bool

Return value

This function returns a new sequence containing all values.

Example 1

The following program demonstrates the usage of the PHP Ds\Sequence::filter() function −

<?php 
   $seq = new \Ds\Set([10, 20, 30, 40, 50]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The filtered sequence: \n";
   print_r($seq->filter(function($val) {
      return $val % 4 == 0; 
   })); 
?>

Output

After executing the above program, the following output will be displayed −

The sequence elements are:
Ds\Set Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The filtered sequence:
Ds\Set Object
(
    [0] => 20
    [1] => 40
)

Example 2

Following is another example of the PHPDs\Sequence::filter()function. We use this function to create a new sequence that contains only odd numbers using the callable function −

<?php 
   $seq = new \Ds\Vector([2, 4, 3, 5, 7, 6, 9, 10]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The filtered sequence(odd numbers): \n";
   print_r($seq->filter(function($val) {
      return $val % 2 != 0; 
   })); 
?>

Output

The above program produces the following output −

The original sequence:
Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 3
    [3] => 5
    [4] => 7
    [5] => 6
    [6] => 9
    [7] => 10
)
The filtered sequence(odd numbers):
Ds\Vector Object
(
    [0] => 3
    [1] => 5
    [2] => 7
    [3] => 9
)
php_function_reference.htm
Advertisements