Jonathan is right. PHP arrays act like map maps to values. in some cases, you can get the index if your array is defined, e.g.
$var = array(2,5); for ($i = 0; $i < count($var); $i++) { echo $var[$i]."\n"; }
your conclusion will be
2 5
and in this case, each element of the array has a knowing index, but if you then do something like the following
$var = array_push($var,10); for ($i = 0; $i < count($var); $i++) { echo $var[$i]."\n"; }
you have no way out. This is because arrays in PHP are not linear structures, as in most languages. They are more like hash tables, which may or may not have keys for all stored values. Consequently, foreach does not use indexes to traverse over them, because they only have an index if the array is defined. If you need to have an index, make sure your arrays are fully defined before going over them and use a for loop.
The Brawny Man Sep 26 '08 at 18:47 2008-09-26 18:47
source share