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

PHP - Ds Sequence::apply() Function



The PHP Ds\Sequence::apply() function is used to update all values of a sequence by applying a callback function to each value. The callback function should return the new value that will replace the existing value in the sequence.

Syntax

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

abstract public Ds\Sequence::apply(callable $callback): void

Parameter

This function accepts a single parameter as a "callback", which is described below −

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

Return value

This function does not return any value.

Example 1

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

<?php  
   $seq = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The updated sequence is: \n";
   $seq->apply(function($val) {
      return $val / 5; 
   });  
   print_r($seq);
?>

Output

The above program produces the following output −

The original sequence:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The updated sequence is:
Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

Example 2

Following is another example of the PHP Ds\Sequence::apply() function. We use this function to update all values of this sequence by invoking the calling function on each value −

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

Output

Once the above program is executed, it displays the following output −

The original sequence:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The updated sequence is:
Ds\Vector Object
(
    [0] => 3
    [1] => 6
    [2] => 9
    [3] => 12
    [4] => 15
)
php_function_reference.htm
Advertisements