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
PHP arrays are both integer-indexed and string-indexed. You can even mix them:
array('red', 'green', 'white', 'color3'=>'blue', 3=>'yellow');
What do you want the index to be for the value 'blue'
? Is it 3? But that's actually the index of the value 'yellow'
, so that would be an ambiguity.
Another solution for you is to coerce the array to an integer-indexed list of values.
foreach (array_values($array) as $i => $value) {
echo "$i: $value\n";
}
Output:
0: red
1: green
2: white
3: blue
4: yellow