PHP - Ds Map::reverse() Function
The PHP Ds\Map::reverse() function reverses the order of the elements in the map in-place. The term in-place means that it modifies the original map without creating or storing any new memory.
Reversing an order of elements in a map means that the first element will be placed at the last position and the last element at the first. For example, if the map is ([1, 2]), the reverse map will be ([2, 1]).
Syntax
Following is the syntax of the PHP Ds\Map::reverse() function −
public Ds\Map::reverse(): void
Parameters
This function does not accept any parameter.
Return value
This function does not return any value but reverses the map elements' order.
Example 1
The following is the basic example of the PHP Ds\Map::reverse() function −
<?php $map = new \Ds\Map([1, 2, 3]); echo "The original map elements are: \n"; print_r($map); echo "The map elements are reversing: \n"; #using reverse() function $map->reverse(); print_r($map); ?>
Output
The above program produces the following output −
The original map elements are:
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => 0
[value] => 1
)
[1] => Ds\Pair Object
(
[key] => 1
[value] => 2
)
[2] => Ds\Pair Object
(
[key] => 2
[value] => 3
)
)
The map elements are reversing:
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => 2
[value] => 3
)
[1] => Ds\Pair Object
(
[key] => 1
[value] => 2
)
[2] => Ds\Pair Object
(
[key] => 0
[value] => 1
)
)
Example 2
Following is another example of the PHP Ds\Map::reverse() function. We use this function to reverse the order of this map (["Tutorials", "Point", "India"]) elements −
<?php
$map = new \Ds\Map(["Tutorials", "Point", "India"]);
echo "The map elements before reversing: \n";
foreach($map as $key=>$value){
echo "[".$key."] = ".$value."\n";
}
echo "The map elements after reversing: \n";
#using reverse() function
$map->reverse();
foreach($map as $key=>$value){
echo "[".$key."] = ".$value."\n";
}
?>
Output
After executing the above program, it will generate the following output −
The map elements before reversing: [0] = Tutorials [1] = Point [2] = India The map elements after reversing: [2] = India [1] = Point [0] = Tutorials