2019-02-04 14:30

# 如何在foreach循环运行的每50次增加一个值1

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

}
?>
``````
• 写回答
• 好问题 提建议
• 关注问题
• 收藏
• 邀请回答

#### 4条回答默认 最新

• dongzha5934 2019-02-04 14:40
已采纳
``````        <?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;
}
}
``````
已采纳该答案
评论
解决 无用
打赏 举报
• dsf4s5787 2019-02-04 14:34

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++;
}
}
?>
``````
评论
解决 无用
打赏 举报
• dongliu8542 2019-02-04 14:37

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.

评论
解决 无用
打赏 举报
• duanmei4149 2019-02-04 14:37
``````\$counter = 1;
\$loop_ctr = 0;
\$increment_by = 1;
foreach(\$numbers as \$num)
{
\$counter+=\$increment_by;
\$loop_ctr++;
if(\$loop_ctr == 50)
{
\$increment_by = 2;
}
}
``````
评论
解决 无用
打赏 举报