PHP - Ds Vector::find() Function
The PHPDs\Vector::find()function is used to find an index of the given value in a vector. The index is the position of elements in a vector where the index 0 represents the first element, 1 represents the second value, and so on.
If the specified value is not present in a vector, this function returns 'false' or an index of the given value.
Syntax
Following is the syntax of the PHP Ds\Vector::find() function −
public mixed Ds\Vector::find( mixed $value )
Parameters
Following is the parameter of this function −
- value − The value needs to be found.
Return value
This function returns an index of the value, or false if not found.
Example 1
The following program demonstrates the usage of the PHP Ds\Vector::find() function −
<?php $vector = new \Ds\Vector([1, 2, 3, 4, 5]); echo "The vector elements are: \n"; print_r($vector); $value = 1; echo "The given value: ".$value; echo "\nThe index of value ".$value." is: "; #using find() function print_r($vector->find($value)); ?>
Output
After executing the above program, the following output will be displayed −
The vector elements are:
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
The given value: 1
The index of value 1 is: 0
Example 2
If the specified value is not present in a vector, this function will return 'false'.
Following is another example of the PHP Ds\Vector::find()function. We use this function to find the index of value "Tutorix" in this vector −
<?php $vector = new \Ds\Vector(["Tutorials", "Point", "India"]); echo "The vector elements are: \n"; print_r($vector); $value = "Tutorix"; echo "The given value: ".$value; echo "\nThe index of the value ".$value." is: "; var_dump($vector->find($value)); ?>
Output
The above program produces the following output −
The vector elements are:
Ds\Vector Object
(
[0] => Tutorials
[1] => Point
[2] => India
)
The given value: Tutorix
The index of the value Tutorix is: bool(false)
Example 3
In the example below, we use the find() function to retrieve the indices of the specified values in a vector −
<?php
$vector = new \Ds\Vector(['a', 10, 'b', "hello", 30, 50 , 'b']);
echo "The vector elements are: \n";
print_r($vector);
echo "The index of value 'a' is: ";
var_dump($vector->find('a'));
echo "The index of value 20 is: ";
var_dump($vector->find(20));
echo "The index of value 'hello' is: ";
var_dump($vector->find("hello"));
echo "The index of value 30 is: ";
var_dump($vector->find(30));
echo "The index of value 'c' is: ";
var_dump($vector->find('c'));
?>
Output
Once the above program is executed, it will display the following output −
The vector elements are:
Ds\Vector Object
(
[0] => a
[1] => 10
[2] => b
[3] => hello
[4] => 30
[5] => 50
[6] => b
)
The index of value 'a' is: int(0)
The index of value 20 is: bool(false)
The index of value 'hello' is: int(3)
The index of value 30 is: int(4)
The index of value 'c' is: bool(false)