The first()
method of the DS\Vector
class in PHP returns the first value present in a vector.
The process is illustrated below:
The prototype of the first()
method is shown below:
mixed public Ds\Vector::first( void )
The first()
method does not accept any parameters.
The first()
method returns the first value present in a vector. This value can have any data type.
If the vector does not contain any values, the first()
method throws the UnderflowException.
The code below shows how the first()
method works in PHP:
<?php// initialize vectors$firstVector = new \Ds\Vector([1, 5, 8, 10, 15]);$secondVector = new \Ds\Vector(["abc", 2, 10, true, false]);// find and print first value of each vectorprint_r($firstVector);print("The first value of the above vector is: ");print($firstVector->first());print("\n\n");print_r($secondVector);print("The first value of the above vector is: " );print($secondVector->first());?>
The above code produces the following output:
Ds\Vector Object
(
[0] => 1
[1] => 5
[2] => 8
[3] => 10
[4] => 15
)
The first value of the above vector is: 1
Ds\Vector Object
(
[0] => abc
[1] => 2
[2] => 10
[3] => 1
[4] =>
)
The first value of the above vector is: abc
Note: To run this program, you need to install Data Structures for PHP on your local machine.
First, two vectors are initialized: firstVector
and secondVector
.
The first()
method in line finds and returns the first value of firstVector
, i.e., the integer .
Similarly, the first()
method in line finds and returns the first value of secondVector
, i.e., the string abc
.
Free Resources