I'm not sure what you are doing, but I can provide you with a simpler way of traversing arrays:
Suppose you wanted to push a couple of names on a array without index. You could do something like this (you'll probably read the values from another source):
$arrFirstNames = array();
$arrFirstNames[] = "Ronnie";
$arrFirstNames[] = "Anders";
$arrFirstNames[] = "Tommy";
$arrFirstNames[] = "Per-olav";
To walk this array and print out the names,
don't use for loops, it only adds complexity.
Using the form below is easier to read and actually more visually appealing 😉
while( list( $nIndex, $sName ) = each( $arrFirstNames ) )
{
echo "[$nIndex] $sName<br>";
}
each() retreives a valuepair of a array in the form: [key][value] and list() extracts values from an array. In this case it extracts and assign the index to $nIndex and the name to $sName.
You elliminate the risk "off-by-one" error by using this approach.
Let's say you wanted to do the same with associative arrays (or whatever the name is).
Start by initialising the array:
$arrNames = array();
$arrNames[ "Ronnie" ] = "Bahlsten";
$arrNames[ "Anders" ] = "Odeskog";
$arrNames[ "Tommy" ] = "Martinsson";
$arrNames[ "Per-olav" ] = "Gramstad";
To walk the array echoing the names, use the suggested approach and do somehing like this:
while( list( $sFirstname, $sLastname ) = each( $arrNames ) )
{
echo "$sFirstname $sLastname <br>";
}
Hmm... I sounded suspiciously much like a teacher 😉
Well, hope that this helped you out a bit.
/ Ronnie