找到你要的答案

Q:Search for the position of an element in a array PHP

Q:对在一个数组元素的位置搜索PHP

There is this array:

$my_array = array("One","two","four");

I need to search for an element and get its position back?

I.e: Searching for "four" would return 2

有这个数组:

$my_array = array("One","two","four");

我需要搜索一个元素并得到它的位置?

即:搜索“四”将返回2

answer1: 回答1:

PHP provides a built-in function for this purpose: array_search().

PHP提供了一个内置的函数用于此目的:array_search()。

answer2: 回答2:

Use array_search():

array_search('four', $my_array);

使用array_search():

array_search('four', $my_array);
answer3: 回答3:

remember array_search() will return the key of the first matching element only. If there are multiple matching elements, you will have to use array_keys() which returns an array of the matching keys.

// Using array_search()
$arr = array ( 0 =>"Apple", 1=>"Orange", 2=>"Lime", 3=>"Peach", 4=>"Lime" );
$key = array_search("Lime", $arr);
echo $key; // outputs 2

// Using array_keys()
$keys = array_keys($arr, "Lime");
echo '<pre>',print_r($keys),'</pre';

outputs

Array
(
    [0] => 2
    [1] => 4
)
1

记得array_search()将返回第一个匹配元素的唯一关键。如果有多个匹配的元素,你将不得不使用array_keys()返回数组的键匹配。

// Using array_search()
$arr = array ( 0 =>"Apple", 1=>"Orange", 2=>"Lime", 3=>"Peach", 4=>"Lime" );
$key = array_search("Lime", $arr);
echo $key; // 输出 2

// Using array_keys()
$keys = array_keys($arr, "Lime");
echo '<pre>',print_r($keys),'</pre';

输出

Array
(
    [0] => 2
    [1] => 4
)
1
php  arrays  search