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

当限制和增量是动态的时,如何获得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.

我见过一些与此相关的问题,如 p>

如何在使用for循环时检查最后一个循环 php? p>

最后 java中增强for循环的迭代 p>

但我没有得到确切的解决方案,因为在我的情况下增量 strong>和结束限制 strong >两者都是动态 strong>。 p>

要求: - strong>我打印最后一个元素后不想使用逗号。 p>

  $ inc = 11;  
 $ end = 100; 
for($ i = 1; $ i&lt; = $ end; $ i = $ i + $ inc){
 echo $ i == $ end?$ i:“$ i,”;  // 1,12,23,34,45,56,67,78,89,100 
} 
  code>  pre> 
 
 

在上面的代码中我知道最后一个元素 ($ i) em>将 100($ end) em>。 p>

所以我可以将条件写为 $ i == $ end strong>,但在下面的情况下它不起作用。 p>

  $ INC = 12;  //现在$ inc是12 
 $ end = 100; 
for($ i = 1; $ i&lt; = $ end; $ i = $ i + $ inc){
 echo $ i == $ end?$ i  : “$ I”;  // 1,13,25,37,49,61,73,85,97,
} 
  code>  pre> 
 
 

现在最后一个元素97有逗号我需要 删除。 p>

提前致谢。 p> div>

You can just use,

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

It checks whether this is the last possible iteration instead.

Use rtrim to remove the last comma

$inc   = 12;  // Now $inc is 12
$end   = 100;

$print = '';
for($i=1;$i<=$end;$i=$i+$inc){
    $print .= ($i==$end)? $i : "$i,";  // 1,13,25,37,49,61,73,85,97,
} 
$print = rtrim($print, ',');
echo $print;

Keep it simple:

$numbers = range(0, $end, $inc);
$string = implode(",", $numbers);
echo $string;

You can see it here: https://3v4l.org/BRpnH

;)

You can do it in this way :

<?php
$inc=4;
$end=10;
for($i=1;$i<=$end;$i=$i+$inc){
    echo ($i+$inc-1)>=$end?$i:"$i,";  // 1,5,9
} 
?>

This code is working on prime number case also not given you result like // 1,13,25,37,49,61,73,85,97, always gives you result like // 1,13,25,37,49,61,73,85,97 no comma added after any prime number.