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

PHP - Ds Sequence::map() Function



The PHP Ds\Sequence::map() function is used to create a new sequence by applying a callback function to each value in the original sequence.

The callback function should be callable and will be invoked for each element in the sequence. It returns the transformed value that will be included in the new sequence.

Syntax

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

abstract public Ds\Sequence::map(callable $callback): Ds\Sequence

Parameters

This function accepts the following parameters −

  • callback − A callable to apply to each value in the sequence.

Following is the syntax of the callback function −

callback(mixed $value): mixed

Return value

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

Example 1

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

<?php
   $seq = new \Ds\Vector([1, 2, 3, 4, 5]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The result of applying callback function: \n";
   print_r($seq->map(function($value) { 
      return $value * 5; 
   }));
?>

Output

The above program produces the following output −

The sequence elements are:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The result of applying callback function:
Ds\Vector Object
(
    [0] => 5
    [1] => 10
    [2] => 15
    [3] => 20
    [4] => 25
)

Example 2

Following is another example of the PHPDs\Sequence::map()function. We use this function to retrieve the result of applying the callback function to each element of this sequence ([10, 20, 30, 40, 50]) −

<?php
   $seq = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The result of applying callback function: \n";
   print_r($seq->map(function($value) { 
      return ($value + 10) * 2; 
   }));
?>

Output

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

The sequence elements are:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The result of applying callback function:
Ds\Vector Object
(
    [0] => 40
    [1] => 60
    [2] => 80
    [3] => 100
    [4] => 120
)
php_function_reference.htm
Advertisements