Jump to content

Nested For Loop


livethedead

Recommended Posts

I'm a bit confused here on for loops. I don't quite understand why this script outputs what it does and I'd like it if someone could explain it to me.

 

<?php
for ($i = 1; $i < 3; $i = $i + 1) {
	for ($j = 1; $j < 3; $j = $j + 1) {
			echo "'i' is {$i}, 'j' is {$j}<br />";
		}
	}
?>

 

Result:

'i' is 1, 'j' is 1
'i' is 1, 'j' is 2
'i' is 2, 'j' is 1
'i' is 2, 'j' is 2

Link to comment
Share on other sites

Your structure runs four times because the outer loop runs two times, and the inner loop (being essentially the same) also runs two times, and 2*2=4. The conditions they run for are i=1, j=1; i=1,j=2; i=2, j=1; and i=2, j=2. The inner loop resets when the outer loop goes to the next iteration. This is nested loop behavior.

 

If you want the loop to run 2x, then the outer loop would need to run 1x and the inner loop would need to run 2x. However, in this case, the outer loop value would not change (as it's only executing once). In other words, it would never increment to 2, it would always be 1 and you would have (1,1) and (1,2), not (1,1) and (2,2).

 

If you want i and j to be the same, you are probably not looking for a nested loop structure. You want:

 

<?php
for ($i=1, $j=1; $i<=2, $j<=2; $i++,$j++) {
	echo "'i' is {$i}, 'j' is {$j}<br />";
}
?>

 

Sorry that was kind of a half-assed question, I was expecting an output like:

1, 1

2, 2

Link to comment
Share on other sites

Nested for-loops are probably best explained with two dimensional arrays.

 

Assume you have an array like:

 

$twoDimArr = array(1 => array(1, 2, 3, 4, 5), 2 => array(1, 2, 3, 4, 5), 3 => array(1, 2, 3, 4, 5), 4 => array(1, 2, 3, 4, 5), 5 => array(1, 2, 3, 4, 5));

// NOTE: The outer array's keys explicitly start at 1.  ALL inner/nested array keys start at 0 in this example

 

We can visualize this structure as a 5x5 table:

 

   1   2   3   4   5
1
2
3
4
5

 

PHP (and other languages) treat two dimensional arrays as row-ordered.  So, when you do something like:

 

echo $twoDimArr[2][3];

 

You access the row at key 2, then the column at key 3 of that row.  Or:

 

   1   2   3   4   5
1
2              x
3
4
5

 

Which is 4 because, again, the inner array's keys start at 0.  So key 3 is the fourth element in that array.

 

When you have nested for-loops, the row-ordering is still in play.  So, something like:

 

   for ($i = 1; $i < 6; ++$i) {
      for ($j = 0; $j < 5; ++$j) {
         echo $twoDimArr[$i][$j];
        
         if ($j == 4) {
            echo "<br />";
         }
      }
   }

 

Will output the arrays row by row.  $j accesses the columns, and $i accesses the rows.

Link to comment
Share on other sites

The $i++ does not get executed until the entire inner-loop has been completed.  Your inner for loop (using $j) is what makes up the body of the outter for loop (using $i).  So each time the $i loop runs (for $i=1 then $i=1) the $j loop will run completely (all the way from $j=1 to $j=2).

 

It might make more sense if you used a different number of iterations for each loop, eg:

for ($i = 1; $i < 4; $i = $i + 1) {
   for ($j = 1; $j < 10; $j = $j + 1) {
       echo "'i' is {$i}, 'j' is {$j}<br />";
   }
}

 

In that case, the $i loop goes from 1 to 3.  The $j loop goes from 1 to 9.  So when it is run it:

//begin

$i=1

  -- $j goes from 1 to 9

$i=2

  -- $j once again goes from 1 to 9

$i=3

  -- $j once again goes from 1 to 9

//Finish

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.