PHP - Ds Vector::find() 函式



PHP 的 Ds\Vector::find() 函式用於在向量中查詢給定值的索引。索引是向量中元素的位置,其中索引 0 表示第一個元素,1 表示第二個值,依此類推。

如果向量中不存在指定的值,則此函式返回 'false' 或給定值的索引。

語法

以下是 PHP Ds\Vector::find() 函式的語法:

public mixed Ds\Vector::find( mixed $value )

引數

以下是此函式的引數:

  • value - 需要查詢的值。

返回值

此函式返回該值的索引,如果未找到則返回 false。

示例 1

以下程式演示了 PHP Ds\Vector::find() 函式的使用:

<?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));
?>

輸出

執行上述程式後,將顯示以下輸出:

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

示例 2

如果向量中不存在指定的值,則此函式將返回 'false'

以下是 PHP Ds\Vector::find() 函式的另一個示例。我們使用此函式在該向量中查詢值“Tutorix”的索引:

<?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));   
?>

輸出

上述程式產生以下輸出:

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)

示例 3

在下面的示例中,我們使用 find() 函式檢索向量中指定值的索引:

<?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'));   
?>

輸出

執行上述程式後,將顯示以下輸出:

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)
php_function_reference.htm
廣告