在PHP中获取数组中某个值的索引 [英] Get the index of a certain value in an array in PHP
本文介绍了在PHP中获取数组中某个值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组:
$list = array('string1', 'string2', 'string3');
我想获取给定值的索引(例如,对于 string2
为 1
,对于 string3
为 2
)
I want to get the index for a given value (i.e. 1
for string2
and 2
for string3
)
我想要的只是字符串在数组中的位置
All I want is the position of the strings in the array
- string1为0
- string2为1
- string3是2
如何实现?
推荐答案
array_search
是做到这一点的方法.
array_search
is the way to do it.
array_search(混合$ needle,数组$ haystack [,bool $ strict = FALSE]):混合
从文档:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
您可以手动循环遍历数组并找到索引,但是为什么要在有此功能的情况下这样做呢?此函数始终返回一个键,并且将与关联数组和普通数组一起很好地工作.
You could loop over the array manually and find the index but why do it when there's a function for that. This function always returns a key and it will work well with associative and normal arrays.
这篇关于在PHP中获取数组中某个值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文