How can I increment a value in a foreach loop for every 50 times the loop runs.
<?php
$counter = 1;
foreach ($numbers as $num) {
//For the first 50 times the loop runs, $counter = 1. For every 50 runs, increment by 1
$counter = 1;
//if loop has run more than 50 times, increment $counter to 2
}
?>
<?php
$counter = 0;
$value = 50; // Intial position
$numbers = 230 // Lets say you have total 230 iterations.
for ($i = 0 ; $i <= $numbers ; i++)
{
if($i == $value) // if 50 counter is increased and we are setting the value to 100
{
$counter += 1;
$value = $value * 2;
}
}
You can use another counter to check when you've done 50 iterations
<?php
$counter = 1;
$MiniCounter = 0;
foreach ($numbers as $num)
{
// Pre-increment since $MiniCounter starts by 0
if (++$MiniCounter >= 50) // using >= 50 because, who knows, $MiniCounter may jump magically from 49 to 51
{
$MiniCounter = 0; //reset the mini counter
$counter++;
}
}
?>
I am not going to provide the full answer because I do not want to encourage questions like this. However, if you really are stuck, just an idea for you, you will need two variables, one will increment each time loop runs and another will check the first variable and will get incremented only when the first variable is divisible by 50.
$counter = 1;
$loop_ctr = 0;
$increment_by = 1;
foreach($numbers as $num)
{
$counter+=$increment_by;
$loop_ctr++;
if($loop_ctr == 50)
{
$increment_by = 2;
}
}