Reputation: 13
How do I create a counter from two for-loops in PHP?
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
}
}
Upvotes: 0
Views: 1059
Reputation: 21230
Unless I'm misunderstanding what you want:
$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;
I think the piece of understanding that you need is about 'scope'. Loosely, anything you see with brackets ({ }
) is probably a new scope, or context. Scopes can generally see the scopes that declared them, but cannot see into scopes they declare. Thus, in the above example, the largest scope is where $counter
is declared, but it cannot see the $y
variable because it is declared in an internal scope.
//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.
Upvotes: 1
Reputation: 27792
Just create a counter variable and increment it in the loop:
$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;
Upvotes: 0
Reputation: 9468
Try this:
$z = 0;
for ($x=9; $x<=12; $x++) {
for ($y=1; $y<=31; $y++) {
echo $y.'<br>';
$z++;
}
}
echo $z;
Add another variable and just count it up.
Upvotes: 1