What is the DS\Vector count() method in PHP?
The count() method of the DS\Vector class in PHP returns the number of values present in a vector.
The process is illustrated below:
The prototype of the count() method is shown below:
int public Ds\Vector::count( void )
Parameters
The count() method does not accept any parameters.
Return value
The count() method returns an integer that represents the number of values present in the vector.
Example
The code below shows how the count() method works in PHP:
<?php// initialize vectors$firstVector = new \Ds\Vector([1, 2, 3, 4, 5]);$secondVector = new \Ds\Vector(["Alice", "Bob", "Charles"]);// print vectors and their countsprint("Printing first vector:\n");print_r($firstVector);print("The count of the first vector is: ");print(count($firstVector));print("\n\nPrinting second vector:\n");print_r($secondVector);print("The count of the second vector is: ");print(count($secondVector));?>
The above code produces the following output:
Printing first vector:
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
The count of the first vector is: 5
Printing second vector:
Ds\Vector Object
(
[0] => Alice
[1] => Bob
[2] => Charles
)
The count of the second vector is: 3
Note: To run this program, you need to install Data Structures for PHP on your local machine.
Explanation
First, two vectors are initialized: firstVector and secondVector. firstVector contains integer values, whereas secondVector contains string values.
The code proceeds to use the count() method in lines and to obtain the number of values in firstVector and secondVector, respectively. The counts are printed along with their respective vectors.
Free Resources