当计数器为偶数但不为零时回显
for ($i=0; $i<=25; $i++) {
if ($i % 2) { is odd } else { is even }
}
我必须从 0 开始,但我不希望它看起来均匀。
for ($i=0; $i<=25; $i++) {
if ($i % 2) { is odd } else { is even }
}
I have to start from 0 but I dont want it to appear as even.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
就是这么简单。继续将导致它跳过循环的此特定迭代的其余部分。您还可以在
继续
之前执行一些代码来处理 0,因为 0 既不是偶数也不是奇数。或者您可以将其作为 if/elseif/else 结构的第一部分。或者代替
if($i % 2)
你可以做if($i % 2 || $i == 0)
这将使它通过奇怪的代码进行处理而不是代码。It's that simple. Continue will cause it to skip the rest of this particular iteration of the loop. You could also do some code to handle 0 before the
continue
, as 0 is neither even nor odd. Or you could make it the first part of the if/elseif/else structure.Or instead of
if($i % 2)
you could doif($i % 2 || $i == 0)
which would make it process through the odd code rather than even code.首先,你真的需要从 0 开始你的 for 循环吗?你可以通过执行
for ($i=1; $i<=25; $i++)
来轻松解决这个问题。如果你确实需要从 0 开始,你实际上可以对这种特殊情况进行测试:
First of all, do you really need starting your for loop from 0? you can easyly work this around by doing
for ($i=1; $i<=25; $i++)
If you really need to start from 0 you can actually put a test for that special case:
或者
OR
就这么简单。
或者如果你想将 0 算为奇数:
It's as simple as this.
Or if you want to count 0 as odd:
如果您只想迭代偶数值,则可以对其进行排序:
If you only want to iterate through the even values, this will sort it:
也许它不是最易读的,但它将是最有效的:
Maybe it's not the most readable but it will be the most efficient:
不幸的是,我认为你需要额外的如果......
I think you need, unfortunately, an extra if...
为什么不在这个已经得到很好回答的帖子中添加 1 个答案:
如果添加
if($i === 0) continue;
它将跳过其余代码并进入下一次迭代。Why not add 1 more answer to this already well answered post:
if you add
if($i === 0) continue;
it will skip the rest of the code and go to the next iteration.