如何从for循环中创建计数器


PHP How to create a counter from for loop

如何在PHP中创建两个for循环的计数器?

for ($x=9; $x<=12; $x++) {
  for ($y=1; $y<=31; $y++) {
    echo $y.'<br>';
    ////// Now it runs well, but I want to add $y into number 
    ///// I know that this loop total run 124 time  so i want 124 
  }
}

试试这个:

$z = 0;
for ($x=9; $x<=12; $x++) {
  for ($y=1; $y<=31; $y++) {
    echo $y.'<br>';
    $z++;
  }
}
echo $z;

除非我误解了你的意思:

$counter = 0;//declare your counter here
for ($x=9; $x<=12; $x++) {
  for ($y=1; $y<=31; $y++) {
    echo $y.'<br/>';//The '$y' variable only exists inside this 'scope'. That is why counter must be declared BEFORE the for-loop.
    $counter++;//Add one for each time it goes through this loop.
  }
}
echo $counter;

我认为你需要理解的是"范围"。粗略地说,您看到的任何带括号的内容({ })都可能是一个新的作用域或上下文。作用域通常可以看到声明它们的作用域,但不能看到它们声明的作用域。因此,在上面的例子中,最大的作用域是声明$counter的地方,但它不能看到$y变量,因为它是在内部作用域中声明的。

//This is the 'outer scope'
$counter = 0;//Any scopes internal to this can see this variable.
for ($x=9; $x<=12; $x++) {//This declares a new scope internal to the outer scope. It can see $counter but not $y.
  for ($y=1; $y<=31; $y++) {//This declares a new scope internal to both other scopes. It can see $x and $counter.
    echo $y.'<br/>';
    $counter++;
  }
  //Note that here we can 'see' $counter and $x, but not $y, even though $y has been declared.
  //This is because when we leave the internal for loop it's 'scope' and any variables associated
  //are discarded and no longer accessible.
}
echo $counter;//At this point only the counter variable is still around, because it was declared by this scope.

创建一个计数器变量并在循环中增加它:

$counter = 0;
for ($x=9; $x<=12; $x++) {
  for ($y=1; $y<=31; $y++) {
    echo $y.'<br>';
    ////// Now it run good but i want add $y into number 
    ///// I know that this loop total run 124 time  so i want 124 
    $counter++;
  }
}
echo $counter;