PHP: watch your temporary loop variables

January 30, 2009 / Filed under: PHP, Programming, Loops, Development

Sometimes in PHP, you'll have a loop within a loop.

An example is the foreach loop:

foreach ($array as $v) {

}

Here we specify that every item in $array is referenced as $v within the loop. Simple enough.

However, what happens when we add another loop inside that loop?

foreach ($array as $v) {

    foreach($another_array as $v) {

    }
}

Here we are accustomed to using the temporary loop variable $v again, but we can't do this for the inner loop. It will conflict with the outer loops' $v. So just change the inner loops' temporary variable to another letter:

foreach ($array as $w) {

    foreach($another_array as $w) {

    }
}

I've seen some strange issues result if loop variables are identical.

Comments/Mentions