2

I have a for loop in my code:

$d = count( $v2['field_titles'] );

for( $i=0; $i < $d; $i++ ) {
  $current = 3 + $i;
  echo 'current is' . $current;
}

How do I know the last iteration if I don't know exact number of $d?

I want to do something like:

$d = count( $v2['field_titles'] );

for( $i=0; $i < $d; $i++ ) {
  $current = 3 + $i;

  if( this is the last iteration ) {
   echo 'current is ' . $current; 
   // add sth special to the output
  }
  else {
    echo 'current is ' . $current;
  }
}
Rafff
  • 1,510
  • 3
  • 19
  • 38
  • $i should be $d - 1, at the last iteration... – njzk2 Oct 20 '14 at 16:16
  • 1
    In this simple case, you just do the `add sth special to the output` after the loop completes. – p.s.w.g Oct 20 '14 at 16:24
  • @Vohuman Not a duplicate at all. Did you read the content or only the title? – JasonMArcher Oct 20 '14 at 16:41
  • @JasonMArcher The idea is the same. A super simple comparison. – Ram Oct 20 '14 at 16:47
  • There is no duplicate like mentioned (1070244), since the other question is about FOREACH loop and the actual question is about a FOR loop. My Approach would be: `if($i+$increase > $sum) { $data->last = true; }` – Francis Jun 23 '17 at 10:17

2 Answers2

5
if($i==$d-1){
   //last iteration :)
}
nicael
  • 18,550
  • 13
  • 57
  • 90
0

I prefer while, to for personally. I would do this:

$array = array('234','1232','234'); //sample array
$i = count($array); 
while($i--){ 
    if($i==0) echo "this is the last iteration"; 
    echo $array[$i]."<br>"; 
}

I've read that this type of loop is a little faster but havn't personally verified. It's certainly easier to read/write, imo.

in your case, this would translate to:

$d = count( $v2['field_titles'] );

while($d--) {
  $current = 3 + $d;

  if($d==0) {
   echo 'current is ' . $current; 
   // add sth special to the output
  }
  else {
    echo 'current is ' . $current;
  }
}
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116