donglu9134 2016-04-15 09:17
浏览 62
已采纳

当限制和增量是动态的时,如何获得for循环的最后一次迭代?

I have seen some question related to this one like

How to check for last loop when using for loop in php?

Last iteration of enhanced for loop in java

but I am not getting exact solution because in my case increment and end limit both are dynamic.

Requirement:- I do not want comma after last element printed.

$inc=11;
$end=100;
for($i=1;$i<=$end;$i=$i+$inc){
    echo $i==$end?$i:"$i,";  // 1,12,23,34,45,56,67,78,89,100
} 

In above code I know that last element($i) will be 100($end).

So I can write condition as $i==$end but in below case it won't work.

$inc=12;  // Now $inc is 12
$end=100;
for($i=1;$i<=$end;$i=$i+$inc){
    echo $i==$end?$i:"$i,";  // 1,13,25,37,49,61,73,85,97,
}

Now last element 97 has comma which I need to remove.

Thanks in advance.

  • 写回答

4条回答 默认 最新

  • dstxpei5823 2016-04-15 09:21
    关注

    You can just use,

    echo $i+$inc>$end?$i:"$i,";
    

    It checks whether this is the last possible iteration instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献