Tutorial :How do you store an integer while in a foreach loop



Question:

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


Solution:1

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


Solution:2

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


Solution:3

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


Solution:4

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';  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »