我怎么知道for循环的最后一次迭代


How do I know the last iteration of for loop?

我的代码中有一个for循环:

$d = count( $v2['field_titles'] );
for( $i=0; $i < $d; $i++ ) {
  $current = 3 + $i;
  echo 'current is' . $current;
}

如果我不知道$d的确切数量,我如何知道最后一次迭代?

我想做一些类似的事情:

$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;
  }
}
if($i==$d-1){
   //last iteration :)
}

我个人更喜欢while,而不是for。我会这样做:

$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>"; 
}

我读到这种类型的循环有点快,但还没有经过个人验证。这当然更容易读/写,我。

在您的情况下,这将转化为:

$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;
  }
}