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

时间:2014-10-20 16:15:14

标签: php 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;
  }
}

2 个答案:

答案 0 :(得分:1)

if($i==$d-1){
   //last iteration :)
}

答案 1 :(得分:0)

我个人更喜欢whilefor。我会这样做:

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

我已经读过这种类型的循环有点快,但没有亲自验证。读取/写入肯定更容易,imo。

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

$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;
  }
}
相关问题