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

PHP - Ds Deque::count() Function



The PHP Ds\Deque::count() function is used to retrieve the number of elements present in the current Deque. It is similar to thelengthandsizemethods or properties in other languages.

You can manually traverse the deque using aforloop and increment a count variable that will be the number of elements. Therefore, the PHP provides the built-in methodcalled count()for quickly determining the number of elements in a deque or other collections.

Syntax

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

public Ds\Deque::count() : int

Parameters

This function does not accept any parameter.

Return value

This function returns the number of elements in the deque.

Example 1

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

<?php
   $deque = new \Ds\Deque(["a", "e", "i", "o", "u"]);
   echo "The deuqe elements are: \n";
   print_r($deque);
   echo "The number of elements in a deque: ";
   print_r($deque->count());
?>

Output

The above program produces the following output −

The deuqe elements are:
Ds\Deque Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The number of elements in a deque: 5

Example 2

Following is another example of the PHP Ds\Deque::count() function. We use this function to find the number of elements present in this deque ([10, 20, 30, 40, 50]) −

<?php
   $deque = new \Ds\Deque([10, 20, 30, 40, 50]);
   echo "The deuqe elements are: \n";
   print_r($deque);
   echo "The number of elements in a deque: ";
   print_r($deque->count());
   $deque->clear();
   echo "\nThe number of elements after clear: ";
   print_r($deque->count());
?>

Output

After executing the above program, the following output will be displayed −

The deuqe elements are:
Ds\Deque Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The number of elements in a deque: 5
The number of elements after clear: 0

Example 3

If the current deque is empty ([]), the count() function returns 0 in the output as follows:

<?php
   $deque = new \Ds\Deque([]);
   echo "The deuqe elements are: \n";
   print_r($deque);
   echo "The number of elements in a deque: ";
   print_r($deque->count());
?>

Output

On executing the above program, it generates the following output −

The deuqe elements are:
Ds\Deque Object
(
)
The number of elements in a deque: 0
php_function_reference.htm
Advertisements