PHP - Ds\Stack::count() Function



The PHPDs\Stack::count()function is used to count the number of elements present in a current stack. If this function is called on an empty ([]) instance, it will return 0, which you can verify using the isEmpty() function whether the stack is empty or not.

Syntax

Following is the syntax of the PHP Ds\Stack::count() function −

public Ds\Stack::count(): int

Parameters

This function does not accept any parameter.

Return value

This function returns the number of values in a stack.

Example 1

The following is the basic example of the PHP Ds\Stack::count() function −

<?php  
   $stack = new \Ds\Stack([2, 4, 6, 8, 10]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The number of elements present in a stack: ";
   #using count() function
   print_r($stack->count());
?>

Output

The above program produces the following output −

The stack elements are:
Ds\Stack Object
(
    [0] => 10
    [1] => 8
    [2] => 6
    [3] => 4
    [4] => 2
)
The number of elements present in a stack: 5

Example 2

Following is another example of the PHP Ds\Stack::count() function. We use this function to find the number of elements present in this (["Tutorials", "Point", "India"]) stack −

<?php  
   $stack = new \Ds\Stack(["Tutorials", "Point", "India"]);
   echo "The stack elements are: \n";   
   print_r($stack);
   echo "The number of elements present in a stack: "; 
   #using count() function
   print_r($stack->count());   
?>

Output

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

The stack elements are:
Ds\Stack Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)
The number of elements present in a stack: 3

Example 3

If the current stack instance is empty ([]), the count() function returns 0.

<?php  
   $stack = new \Ds\Stack([]);
   echo "The stack elements are: \n";   
   print_r($stack);
   echo "The number of elements present in a stack: "; 
   #using count() function
   print_r($stack->count()); 
?>

Output

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

The stack elements are:
Ds\Stack Object
(
)
The number of elements present in a stack: 0
php_function_reference.htm
Advertisements