PHP-从数组中获取元素的索引 [英] PHP - Getting the index of a element from a array

查看:880
本文介绍了PHP-从数组中获取元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遍历数组时如何获取当前元素编号?

How can I get the current element number when I'm traversing a array?

我了解count(),但是我希望有一个内置函数也可以获取当前字段索引,而不必添加额外的计数器变量.

I know about count(), but I was hoping there's a built-in function for getting the current field index too, without having to add a extra counter variable.

像这样:

foreach($array as $key => value)
  if(index($key) == count($array) ....

推荐答案

您应使用 key()函数

key($array)

应返回当前密钥.

如果需要当前键的位置:

If you need the position of the current key:

array_search($key, array_keys($array));

这篇关于PHP-从数组中获取元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆