php 在简单数组中查找元素的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3804354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:10:54  来源:igfitidea点击:

Finding the position of an element in a simple array

phparrays

提问by Psyche

Let's say we have this array:

假设我们有这个数组:

Array ( [0] => 10 [1] => 45 [2] => 23 ) 

How can I determine the position of element '45' in this array?

如何确定此数组中元素“45”的位置?

I'm using PHP.

我正在使用 PHP。

Thank you.

谢谢你。

回答by Gumbo

Use array_searchto get the key to a value:

使用array_search得到的关键价值:

$key = array_search(45, $arr);

And if you want to get its position in the array, you can search for the index of the key in the array of keys:

如果你想得到它在数组中的位置,你可以在键的数组中搜索键的索引:

$offset = array_search($key, array_keys($arr));

So with an array like the following you will still get 1as result:

因此,使用如下所示的数组,您仍然会得到1结果:

$arr = array('foo' => 10, 'bar' => 45, 'baz' => 23);

回答by Felix Kling

Google to the rescue: array_search

谷歌救援: array_search