Home > Coding Tips > Classic Programming Error: Variables inside a loop

Classic Programming Error: Variables inside a loop

March 25th, 2010 Leave a comment Go to comments

This for loop is OK

foreach($cargo_data as $cid=>$cargo_record)
{
$cargo_id=$cargo_data[$cid][‘cargo_id’];
$section=$cargo_data[$cid][‘section’];

}

But then later you add a condition cargo_id>6

foreach($cargo_data as $cid=>$cargo_record)
{
if ($cid>6) {$cargo_id=$cargo_data[$cid][‘cargo_id’];}
$section=$cargo_data[$cid][‘section’];

}

Now the bug is that if $cid is less than 6 $cargo_id is not set and will likely inherit the value it was set to in the last loop this type of error may not be immediately noticeable but can cause chaos. In this simple example it is easy to see that their should be an else clause, however the real solution is to systematically initialize all the variables at the beginning of the loop.

Categories: Coding Tips Tags:
  1. No comments yet.
  1. No trackbacks yet.