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

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.