PHP - Ds Map::capacity() Function
The PHPDs\Map::capacity()function is used to retrieve the current capacity of a map. This function also returns the current capacity of other collections, such as a "set" or "deque" in thePHP Ds extension.
The capacity represents the internal memory allocation for the map, which determines how many elements the map can hold efficiently. You can also explicitly allocate a custom capacity using theallocate() function.
Suppose, you add more elements to the map and exceed its current capacity, it will automatically allocate additional memory for the new elements.
Syntax
Following is the syntax of the of the PHP Ds\Map::capacity() function −
public Ds\Map::capacity(): int
Parameters
This function does not accept any parameter.
Return value
This function returns the current capacity of a map.
Example 1
The following program demonstrates the usage of the PHP Ds\Map::capacity() function −
<?php $map = new \Ds\Map(); echo "The map elements are: "; print_r($map); echo "The current capacity of this map: "; #using capacity() function print_r($map->capacity()); ?>
Output
After executing the above program, it will display the following output −
The map elements are: Ds\Map Object ( ) The current capacity of this map: 8
Example 2
Following is another example of the PHP Ds\Map::capacity() function. We use this function to retrieve the current capacity of this map ([10, 20, 30]) −
<?php
$map = new \Ds\Map([10, 20, 30]);
echo "The map elements are: \n";
foreach ($map as $key => $value) {
echo "[".$key."] => ".$value."\n";
}
echo "The capacity of this map (initial): ";
#using the capacity() function
print_r($map->capacity());
#using the allocate() function
$map->allocate(64);
echo "\nThe capacity of this map after allocating new capacity: ";
print_r($map->capacity());
?>
Output
Once the above program is executed, it will display the following output −
The map elements are: [0] => 10 [1] => 20 [2] => 30 The capacity of this map (initial): 8 The capacity of this map after allocating new capacity: 64