note 9446 deleted from control-structures.foreach by sniper
| From: | sniper@php.net | Date: | Wed, 08 Oct 2003 04:12:23 +0000 |
| Subject: | note 9446 deleted from control-structures.foreach by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-58022@lists.php.net to get a copy of this message | ||
Note Submitter: orque@mac.com
----
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.