tags:

views:

75

answers:

5

Hi

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) ....
+1  A: 
foreach() {
    $i++;
    if(index($key) == $i){}
    //
}
Galen
he said without having to add a extra counter variable
rideon88
@rideon OPs often have odd wishes. Don't take it too literally ;) Actually this one should be accepted.
Col. Shrapnel
+1  A: 

There is no way to get a position which you really want.
For associative array, to determine last iteration you can use already mentioned counter variable, or determine last item's key first:

end($array);
$last = key($array);
foreach($array as $key => value)
  if($key == $last) ....
Col. Shrapnel
+2  A: 

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));
Zahymaka
the OP wants a position, not a key. No need to get a kay as it;a already assigned to $key variable
Col. Shrapnel
I just realized that. I made a modification.
Zahymaka
+1 Good answer, I would just like to point out to Alex that adding a counter would be more efficient that searching the array each time though.
Gazler
so there's no index-like function. thanks :) I'll just use a counter
Alex
I'd dovnvote it as it's seems way overkill to me. 2 additional loops over whole array per iteration!
Col. Shrapnel
+2  A: 

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
Bill Karwin
A: 

an array does not contain index when elements are associative. An array in php can contain mixed values like this:

$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");   
print_r($var);

Gives you:

Array
(
    [0] => apple
    [1] => banana
    [foo] => grape
    [2] => carrot
    [bar] => donkey
)

What are you trying to achieve since you need the index value in an associative array?

thomasmalt