,

PHP foreach bug and how to fix it


As I am also a PHP programmer, sometimes the quirks of PHP irks me. There was this time when I was working on a project and the deadline was very near. I was coding in near panic mode and suddenly code that should work, failed miserably.

It was a simple loop and I was using foreach to iterate through an array and do something. Little did I know that I had hit upon a foreach bug. I had code similar to below:

    $students = array(‘ram’, ‘shyam’, ‘hari’);
    foreach( $students as $row )
      echo “<br/>$row”;
    // unset($row);

    $marks = array(65,75,85);
    foreach( $marks as $row )
      echo “<br/>$row”;

It should work without any problem right? Wrong! The first loop will work great but you cannot be 100% sure that the second loop will work. Sometimes it might work, sometimes it might not, but the biggest problem is that you can never be sure when it will break.

The solution: unset variables

The solution is simple — To fix the foreach bug, simply unset the variable you are using during iteration. In the above example, simply uncomment the line of code where $row is unset.

image source

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.