note 9446 added to foreach
| From: | orque at mac dot com | Date: | Fri, 03 Nov 2000 16:30:09 +0000 |
| Subject: | note 9446 added to foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-7344@lists.php.net to get a copy of this message | ||
From my recent frustration, I realized foreach iterates over the array in the order it was *created*
and not a step progression as if you were using a for loop.
i.e. say we have an array that represents rows and columns and its size was unknown to begin with.
Now say we start filling it in out of order but eventually the we have the same number of columns
for every row. In a for loop we would have
for ($i = 0; $i < $rows; $i++){
for ($j = 0; $j < $cols; $j++){
echo("value:".$array[$i][$j]);
}
}
now say we wanted to do the same thing with a foreach loop:
foreach($array as $row){
foreach($row as $column){
echo("value: $column");
}
}
it returns values *in the order they were created*. So if, while we were making the array, we put in
[0][0] = 1, [0][1] = 2, [1][1] = 3, [1][0] = 4, the foreach will print 1, 2, 3, 4 instead of the
desired 1, 2, 4, 3.
http://www.php.net/manual/control-structures.foreach.php