Posted by peter on 03/24/07 11:21
> I have no trouble looping through an array using foreach. To keep
> track of the index, I set a variable before the loop and increment it
> in the loop:
>
> $index = 0;
> foreach ($array as $item) {
> blah;
> $index++;
> do something that requires knowing the index of the current item;
> }
>
> Is there a better way to access that index value?
As mike and kim suggested use foreach ($array as $index=>$item) {
Also something that has not been raised. You pseudo exemple is somewhat
flawed so I thought it best to point it out.
In your example you are incrementing the index before you use it and the
index starts at 0. Array's are zero based meaning the first element of the
array has the key 0 the second 1 etc. In your example you would have 1 as
being the first and 2 being the second.:-
<?php
$test = array('a','b');
print_r($test)
?>
The above code shows this.
Navigation:
[Reply to this message]
|