PHP - Ds Deque::filter() Function



The PHPDs\Deque::filter()function is used to create a new deque using a callback function. The callback function returns a Boolean value ('true' or 'false') and, based on the returned value, the function determines whether a value should be included in the new deque.

If a callback is not provided to this function, only those values will be included that are converted to 'true'.

Syntax

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

public Ds\Deque::filter(callable $callback = ?): Ds\Deque

Parameters

This function accepts an optional parameter named 'callback', which is described below −

  • callback − It is an optional callable function that returns 'true' if the value should be included, and 'false' otherwise.

Return value

This function returns a new deque containing all the elements for which the callback returned 'true'.

Example 1

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

<?php
   $deque = new \Ds\Deque([1, 2, 3, 4, 5]);
   echo "The original deque elements are: \n";
   print_r($deque);
   echo "The new deque elements after the filter: \n";
   print_r($deque->filter(function($value) {
      return $value % 2 == 0;
   }));
?>

Output

The above program produces the following output −

The original deque elements are:
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The new deque elements after the filter:
Ds\Deque Object
(
    [0] => 2
    [1] => 4
)

Example 2

Following is another example of the PHP Ds\Deque::filter() function. We use this function to create a new deque containing all the values for which the callback returns 'true' −

<?php
   $deque = new \Ds\Deque([1, 5, 10, 15, 20]);
   echo "The original deque: \n";
   print_r($deque);
   echo "The new deque after filter: \n";
   print_r($deque->filter(function($value) {
      return $value+($value+1) == 42;
   }));
?>

Output

After executing the above program, it displays the following output −

The original deque:
Ds\Deque Object
(
    [0] => 1
    [1] => 5
    [2] => 10
    [3] => 15
    [4] => 20
)
The new deque after filter:
Ds\Deque Object
(
)

Example 3

If the callback function is omitted, the PHP Ds\Deque::filter() function creates a new deque that contains all the values which converted to 'true' as follows −

<?php
   $deque = new \Ds\Deque([10, 20, 30]);
   echo "The original deque: \n";
   print_r($deque);
   echo "The deque after filter: \n";
   print_r($deque->filter());
?>

Output

Once the above program is executed, it will generate the following output −

The original deque:
Ds\Deque Object
(
    [0] => 10
    [1] => 20
    [2] => 30
)
The deque after filter:
Ds\Deque Object
(
    [0] => 10
    [1] => 20
    [2] => 30
)
php_function_reference.htm
Advertisements