PHP - Getting the index of a element from a array

Alex picture Alex · Sep 21, 2010 · Viewed 125.8k times · Source

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

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.

like this:

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

Answer

Zahymaka picture Zahymaka · Sep 21, 2010

You should use the key() function.

key($array)

should return the current key.

If you need the position of the current key:

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