PHP - Ds Map::clear() Function



The PHP Ds\Map::clear() function is used to remove all values in the current map. If the map on which we are calling this function is already empty, it does not affect the map, and it will remain unchanged.

Once the clear() function is called, the current map will be empty. You can verify this using the isEmpty() function, which returns 'true' if the map is empty and 'false' otherwise.

Syntax

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

public Ds\Map::clear(): void

Parameters

This function does not accept any parameter.

Return value

This function does not return any value.

Example 1

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

<?php 
   $map = new \Ds\Map([1, 2, 3, 4, 5]);
   echo "The map elements are: \n";
   foreach($map as $key=>$value){
   echo "[".$key."]"." = ".$value."\n";
   }
   #using clear() function
   $map->clear(); 
   echo "The map after the clear() function called: \n";
   print_r($map); 
?>

Output

The above program produces the following output −

The map elements are:
[0] = 1
[1] = 2
[2] = 3
[3] = 4
[4] = 5
The map after the clear() function called:
Ds\Map Object
(
)

Example 2

Following is another example of the PHP Ds\Map::clear() function. We use this function to clear all the values of this map (["Tutorials", "Point", "India"]) −

<?php 
   $map = new \Ds\Map(["Tutorials", "Point", "India"]);
   echo "The map elements are: \n";
   foreach($map as $key=>$value){
   echo "[".$key."]"." = ".$value."\n";
   }
   #using clear() function
   $map->clear(); 
   echo "The map after the clear() function called: \n";
   print_r($map); 
?>

Output

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

The map elements are:
[0] = Tutorials
[1] = Point
[2] = India
The map after the clear() function called:
Ds\Map Object
(
)

Example 3

If the current map is already empty, on which we are calling the clear() function does not affect the map, and the map will remain unchanged −

<?php 
   $map = new \Ds\Map([]);
   echo "The map elements are: \n";
   foreach($map as $key=>$value){
   echo "[".$key."]"." = ".$value."\n";
   }
   #using clear() function
   $map->clear(); 
   echo "The map after the clear() function called: \n";
   print_r($map); 
?>

Output

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

The map elements are:
The map after the clear() function called:
Ds\Map Object
(
)
php_function_reference.htm
Advertisements