網頁

2013年9月9日 星期一

last element foreach loop in PHP

Find the last element of an array while using a foreach loop in PHP

   
$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
  if(++$i === $numItems) {
    echo "last index!";
  }
} 

PDOStatement::rowCount

Syntax with "endforeach" used mostly in complex templates where easier to find "endforeach" than "}":
<?php
foreach ($arr as $key => $value):
 echo 'Key: '.$key.' Value: '.$value."<br />\n";
endforeach; 
?>
Classic syntax:
<?php
foreach ($arr as $key => $value){
 echo 'Key: '.$key.' Value: '.$value."<br />\n";
}
?>

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。