What is the Ds\Map::map() function in PHP?

The map class in PHP is a collection of key-value pairs. The structure of a map is similar to an array in terms of the sequenceinsertion order is preserved, performance, and memory efficiency.

The map() function is used to apply a callback function on each value within the map.

The Ds\Map::map() method for a callback function that uppercases the values

Syntax

Below is the function prototype.

Ds\Map public Ds\Map::map (callable $callback)

Parameters and return value

The map() function takes the following input parameter.

  • $callback: The callback function to be applied on each value.

Note: The callback function must return the appropriate data type for the values in the map.

The map() function returns a new map in which the callback function has been applied for each value. This means that the original map values remain unaffected.

Code

<?php

// Creating a Map
$map = new \Ds\Map(["0" => "a", 
            "1" => "b", "2" => "c", "3" => "d", "4" => "e", "5" => "f"]);
  

$newmap = $map->map(function($key, $value){
                    return strtoupper($value);});
                    
// Print new map
echo "New Map: \n";
print_r($newmap);

echo"--------------------------------------\n";
  
// Print original map
echo "Original Map: \n";
print_r($map);
  
?>

Output

New Map:
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => 0
[value] => A
)

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

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

[3] => Ds\Pair Object
(
[key] => 3
[value] => D
)

[4] => Ds\Pair Object
(
[key] => 4
[value] => E
)

[5] => Ds\Pair Object
(
[key] => 5
[value] => F
)

)
--------------------------------------
Original Map:
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => 0
[value] => a
)

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

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

[3] => Ds\Pair Object
(
[key] => 3
[value] => d
)

[4] => Ds\Pair Object
(
[key] => 4
[value] => e
)

[5] => Ds\Pair Object
(
[key] => 5
[value] => f
)

)

Explanation

In the example above, the callback function merely takes the value and changes it to uppercase. The resulting map is stored in the $newmap variable.

Both the new map and the original map are printed. The original map is unaffected, while the new map now has all values in uppercase.

Note: To run this program, you must first install Data Structures for PHP on your local machine.

Free Resources