A better for loop

February 18th, 2011 § 3 comments § permalink

A simple for loop in a better way

Our regular for loop

$arr = array(10,20,30,40);
$sum = 0;
for($i=0;$i<count($arr);$i++){
      $sum += $arr[$i];
}
echo $sum;

A better option

$arr = array(10,20,30,40);
$sum = 0;
$count = count($arr);
for($i=0;$i<$count;$i++){
       $sum += $arr[$i];
}
echo $sum;

U need even more better option??

$arr = array(10,20,30,40);
$sum = 0;
$count = count($arr);
for($i=$count;$i--;){
     $sum += $arr[$i];
}
echo $sum;