Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Ds Deque::map() Function



The PHP Ds\Deque::map() function is used to retrieve the result of applying a callback function to each value.

This function is used to apply the specified callback function to every element of the deque and update the deque with the results obtained by this function. The updated deque is the output of this function.

Syntax

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

public Ds\Deque::map(callable $callback): Ds\Deque

Parameters

Following is the parameter of this function −

  • callback − A function that returns the new value that is to be replaced in the new deque.

Return value

This function returns the result of applying a callback to each value in the deque.

Example 1

The following is the basic example of the PHP Ds\Deque::map() function −

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

Output

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

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

Example 2

Following is another example of the PHP Ds\Deque::map() function. We use this function to retrieve the result of applying a callback to each value in this deque ([74, 99, 177, 66, 198, 121, 154]) −

<?php
   $deq = new \Ds\Deque([74, 99, 177, 66, 198, 121, 154]);
   echo "The original deque: \n";
   print_r($deq);
   echo "The result of applying callback function: \n";
   print_r($deq->map(function($element) {
       return $element%11 ;
   }));
?>

Output

The above program produces the following output −

The original deque:
Ds\Deque Object
(
    [0] => 74
    [1] => 99
    [2] => 177
    [3] => 66
    [4] => 198
    [5] => 121
    [6] => 154
)
The result of applying callback function:
Ds\Deque Object
(
    [0] => 8
    [1] => 0
    [2] => 1
    [3] => 0
    [4] => 0
    [5] => 0
    [6] => 0
)
Advertisements