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

PHP - DsMap::reversed() Function



The PHP Ds\Map::reversed() function is used to retrieve a reversed copy of a map. This function does not affect the current instance, instead, it returns a new reversed map.

The term "a reversed copy of a map" refers to a new map where the first element is placed at the last position, the last elements are placed at the first position, and so on in the original map.

Syntax

Following is the syntax of the PHP Ds\Map::reversed() function −

public Ds\Map::reversed(): Ds\Map

Parameters

This function does not accept any parameter.

Return value

This function returns a reversed copy of a map.

Example 1

The following is the basic example of the PHP Ds\Map::reversed() function −

<?php 
   $map = new \Ds\Map([10, 20, 30]); 
   print("The original map: \n"); 
   print_r($map); 
   $reversedMap = new \Ds\Map(); 
   $reversedMap = $map->reversed(); 
   print("\nThe reversed copy of a map: \n"); 
   print_r($reversedMap); 
?>

Output

Once the above program is executed, it will display the following output −

The original map:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => 10
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => 20
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => 30
        )

)

The reversed copy of a map:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 2
            [value] => 30
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => 20
        )

    [2] => Ds\Pair Object
        (
            [key] => 0
            [value] => 10
        )

)

Example 2

Following is another example of the PHP Ds\Map::reversed() function. We use this function to retrieve the reversed copy of this map (['a', 'e', 'i', 'o', 'u']) −

<?php 
   $map = new \Ds\Map(['a', 'e', 'i', 'o', 'u']); 
   print("The original map: \n"); 
   foreach($map as $key=>$value){
	   echo "[".$key."] = ".$value."\n";
   }
   $reversedMap = new \Ds\Map(); 
   $reversedMap = $map->reversed(); 
   print("\nThe reversed copy of a map: \n"); 
   foreach($reversedMap as $key=>$value){
	   echo "[".$key."] = ".$value."\n";
   } 
?>

Output

After executing the above program, it will display the following output −

The original map:
[0] = a
[1] = e
[2] = i
[3] = o
[4] = u

The reversed copy of a map:
[4] = u
[3] = o
[2] = i
[1] = e
[0] = a
php_function_reference.htm
Advertisements