tags:

views:

118

answers:

4

This may be simple to some of you guys but im a novice coder. How do i make this foreach loop terminate after i loops. The number keeps resetting as it loops through another condition. There are multiple a's. About 100 so it i never gets up to 250.

$i = 0;

foreach ($a as $b) {
   //do function

   i++;

   if (i == 250)
   {
     exit;
   }
}
+6  A: 

You're missing a "$" sign on two of your "i"s. It should be:

$i = 0;

foreach ($a as $b) {
   //do function

   $i++;

   if ($i == 250)
   {
     exit;
   }
}
da5id
And the increment too. Good catch, I missed it myself. Used to C.
JoostK
+3  A: 

$i should not reset, because it was declared outside of the for-loop. However, there in a syntax error within that snippet:

$i = 0;

foreach($a as $b)
{
   // do something with $b
   if(++$i == 250) exit;
}
Anthony M. Powers
da5ids's comment is the same: You've just forgotten to add the '$' symbol in front of the 'i' variable within the forloop, so you weren't actually changing the value of '$i'...
Anthony M. Powers
+2  A: 

You're missing the dollar sign ($) before your variable i within the loop:

$i = 0;
foreach ($a as $b)
{  
    //do function  
    $i++;    
    if ($i == 250)
    {
        exit; // or break;
    }   
}
Jordan Ryan Moore
+1  A: 

If $a only contains an array of about 100 elements as you said, then there is no need to check that $i is 250. After the code has gone through all the elemnents in $a, then the foreach loop will exit and you will go on to the next code.

foreach($a as $b) {
  echo $b . '<br />';
}

echo 'Loop has finished';

If you are looking to keep count, you should use for instead:

for ($i = 0; $i < count($a); $i++) {
  echo 'Element ' . $i . ' is ' . $a[$i] . '<br />';
  if ($i == 250) {
    break; // this will exit the loop
  }
}

echo 'Loop has finished';
Matt McCormick