如何在foreach中增加变量
I have 2 foreachs, one inside the other.
In the second one, I'm trying to increment a variable.. But it is being reseted in each loop...
Check it out...
$i2 = 0;
foreach($result as $line) {
echo "Foreach begins. i2 =".$i2; // Foreach begins. i2 = 0
$i2++;
echo "i2 incremented. i2 =".$i2; // i2 incremented. i2 = 1
}
But the loop result shows me this text:
Foreach begins. i2 = 0
i2 incremented. i2 = 1
Foreach begins. i2 = 0
i2 incremented. i2 = 1
I'm trying to get:
Foreach begins. i2 = 0
i2 incremented. i2 = 1
Foreach begins. i2 = 1
i2 incremented. i2 = 2
What's wrong?
我有2个foreach,一个在另一个内。 p>
在第二个 一,我正在尝试增加一个变量..但它正在每个循环中被重置... p>
检查出来...... p>
$ i2 = 0;
foreach($ result as $ line){
echo“Foreach starts.i2 =”。$ i2; // Foreach开始了。 i2 = 0
$ i2 ++;
echo“i2递增.i2 =”。$ i2; // i2递增 i2 = 1
}
code> pre>
但循环结果显示此文本: p>
Foreach开始。 i2 = 0
i2递增。 i2 = 1
Foreach开始。 i2 = 0
i2递增。 我正在尝试获取: p>
i2 = 0
i2递增。 i2 = 1
Foreach开始。 i2 = 1
i2递增。 i2 = 2
code> pre>
出了什么问题? p>
div>
I presume you have that loop inside another one that looks this this:
foreach($thing as $result) {
$i2 = 0;
foreach($result as $line) {
echo "Foreach begins. i2 =".$i2; // Foreach begins. i2 = 0
$i2++;
echo "i2 incremented. i2 =".$i2; // i2 incremented. i2 = 1
}
}
Your issue is that in each loop of the original (first) foreach()
, you're resetting the $i2
variable.
Simply move that variable out of the first foreach()
scope and it should work:
$i2 = 0;
foreach($thing as $result) {
foreach($result as $line) {
echo "Foreach begins. i2 =".$i2; // Foreach begins. i2 = 0
$i2++;
echo "i2 incremented. i2 =".$i2; // i2 incremented. i2 = 1
}
}
Is there any reason you are using the second for each loop? If all you are trying to do with the second loop is to increment some numbers then perhaps it should be a for loop with a for each inside of it like noted here for each loop inside of for loop
Simply initialize the $i2 variable outside of the foreach loop and that's it.
Like this:
$i2 = 0;
foreach(){
foreach(){
$i2++;
}
}