PHP - Ds Deque::apply() Function



The PHPDs\Deque::apply()function is used to update all the values of the Deque by applying a callback function to each value in a deque.

The callback function must return a value so that the old value of deque will be replaced with the return value by the callback function.

Syntax

Following is the syntax of the PHP Ds\Deque::apply() function βˆ’

public Ds\Deque::apply(callable $callback): void

Parameters

This function accepts a single parameter as a "callback" function, which is described below βˆ’

  • callback βˆ’ It represents a callable function that applies to each value in a deque.

Return value

This function does not return any value.

Example 1

The following program demonstrates the usage of the PHP Ds\Deque::apply() function βˆ’

<?php 
   $deque = new \Ds\Deque([1, 2, 3, 4, 5]); 
   echo("The original deque: \n"); 
   print_r($deque);
   $deque->apply(function($element) {  
      return $element * 5;  
   });  
   echo("The updated deque: \n"); 
   print_r($deque); 
?>

Output

After executing the above program, it displays the following output βˆ’

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

Example 2

Following is another example of the PHP Ds\Deque::apply() function. We use this function to update all the values of this deque ([10, 20, 30, 40, 50, 60]) by applying the provided callback function that returns the mod with 10 of each element βˆ’

<?php 
   $deque = new \Ds\Deque([10, 20, 30, 40, 50, 60]);  
   echo("The original deque: \n"); 
   print_r($deque);
   $deque->apply(function($element) {  
      return $element % 10;  
   }); 
   echo("The updated deque: \n"); 
   print_r($deque);
?>

Output

The above program produces the following output βˆ’

The original deque:
Ds\Deque Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
    [5] => 60
)
The updated deque:
Ds\Deque Object
(
    [0] => 0
    [1] => 0
    [2] => 0
    [3] => 0
    [4] => 0
    [5] => 0
)

Example 3

In the example below, we use the apply() function to update this deque ([0, 0, 0, 0]) element values by adding 10 in each element using the provided callback function βˆ’

<?php 
   $deque = new \Ds\Deque([0, 0, 0, 0]);  
   echo("The original deque: \n"); 
   print_r($deque);
   $deque->apply(function($element) {  
      return $element + 10;  
   }); 
   echo("\nThe updated deque: \n"); 
   print_r($deque); 
?>

Output

On executing the above program, it generates the following output βˆ’

The original deque:
Ds\Deque Object
(
    [0] => 0
    [1] => 0
    [2] => 0
    [3] => 0
)

The updated deque:
Ds\Deque Object
(
    [0] => 10
    [1] => 10
    [2] => 10
    [3] => 10
)
php_function_reference.htm
Advertisements