0

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.

Community
  • 1
  • 1
Ravi Hirani
  • 6,511
  • 1
  • 27
  • 42
  • is it critical to use for loop instead of while(condition)? – heximal Apr 15 '16 at 09:19
  • 2
    You can just check if the next iteration with the increment will run or not: `echo $i + $inc >$end?$i:"$i,";` – Rizier123 Apr 15 '16 at 09:21
  • Why don't you just make an array of the incremented elements and then use implode function with comma as a glue? you wouldn't have to worry about any of this if you use implode instead. – Lauri Orgla Apr 15 '16 at 09:23
  • @Rizier123: Thanks brother. It is working like a charm :-) – Ravi Hirani Apr 15 '16 at 09:38
  • @LauriOrgla: I am already in loop so it is not a good idea to store all elements in array and then use implode. – Ravi Hirani Apr 15 '16 at 09:44
  • @RaviHirani If you had gazillion items, then yes. But your example shows from 1 to 100. You wanted working solution, i gave you one. Otherwise you would have to determine in the loop whether the element you are working with is the last one. If not, then append a comma. – Lauri Orgla Apr 15 '16 at 09:47

4 Answers4

3

Keep it simple:

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

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

;)

1

You can just use,

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

It checks whether this is the last possible iteration instead.

Imesha Sudasingha
  • 3,462
  • 1
  • 23
  • 34
0

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;
J.K
  • 1,382
  • 1
  • 11
  • 27
0

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.

jilesh
  • 436
  • 1
  • 3
  • 13