PHP - Ds Vector::map() Function
The PHP Ds\Vector::map() function is used to retrieve the result of applying a callback to each value of a vector. This function does not affect the current instance instead, it returns a new result.
The "callback" is a callable function that should return what the new value will be in the new vector.
Syntax
Following is the syntax of the PHP Ds\Vector::map() function −
public Ds\Vector::map(callable $callback): Ds\Vector
Parameters
Following is the parameter of this function −
- callback − A callable function applies to each value.
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 vector.
Example 1
The following program demonstrates the usage of the PHP Ds\Vector::map() function −
<?php
$vector = new \Ds\Vector([1, 2, 3, 4, 5]);
echo "The original vector: \n";
print_r($vector);
echo "The result of applying callback function: \n";
print_r($vector->map(function($value) {
return $value * 5;
}));
?>
Output
After executing the above program the following output will be displayed −
The original vector:
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 PHP Ds\Vector::map() function. We use this function to retrieve the result by applying the callback function on each element of this vector ([5, 15, 25, 35, 45]) −
<?php
$vector = new \Ds\Vector([5, 15, 25, 35, 45]);
echo "The original vector is: \n";
print_r($vector);
echo "The result of applying callback function: \n";
var_dump($vector->map(function($value) {
return $value <= 30;
}));
?>
Output
The above program produces the following output −
The original vector is:
Ds\Vector Object
(
[0] => 5
[1] => 15
[2] => 25
[3] => 35
[4] => 45
)
The result of applying callback function:
object(Ds\Vector)#3 (5) {
[0]=>
bool(true)
[1]=>
bool(true)
[2]=>
bool(true)
[3]=>
bool(false)
[4]=>
bool(false)
}