A better for loop

February 18th, 2011 § 3 comments

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;

Revath S Kumar [RSK]

- Rubyist / JavaScripter - Yeoman Team member - Open source enthusiast - Blogger @ PHPRepo and http://blog.revathskumar.com - Coder @ Whatznear - Google fanboy - jQuery lover

More Posts - Website - Twitter - Facebook - LinkedIn - Pinterest - Google Plus - YouTube

Tagged

  • What about:

    $arr = array(10,20,30,40);
    $sum = 0;
    foreach($arr as $value){
    $sum +=$value;
    }
    echo $sum;

    for loops are not really a good approach when you can do it in a foreach loop.

    • RSK

      Yes, I understand. i just want to share this is a better way to write the for loop.
      thankz.

    • I do agree with it 🙂

      @Revath: Good for the beginners 🙂