Jump to content

clarification on forloop working...


karthikanov24

Recommended Posts

hi

what are the values of $i,the for loop takes and at what value of $i it enters the last if loop to print  

whether it leaves the for loop when $i reaches the value '1'  or leaves after increasing to value '2'...?

 

$categoryList    = getCategoryList();
$categoriesPerRow = 3;
$numCategory     = count($categoryList);
$columnWidth    = (int)(100 / $categoriesPerRow);
?>
<table width="100%" border="0" cellspacing="0" cellpadding="20">
<?php 
if ($numCategory > 0) {
$i = 0;
for ($i; $i < $numCategory; $i++) {
	if ($i % $categoriesPerRow == 0) {
		echo '<tr>';
	}

	// we have $url, $image, $name, $price
	extract ($categoryList[$i]);

	echo "<td width=\"$columnWidth%\" align=\"center\"><a href=\"$url\"><img src=\"$image\" border=\"0\"><br>$name</a></td>\r\n";


	if ($i % $categoriesPerRow == $categoriesPerRow - 1) {
		echo '</tr>';
	}

}

if ($i % $categoriesPerRow > 0) {
	echo '<td colspan="' . ($categoriesPerRow - ($i % $categoriesPerRow)) . '"> </td>';
}
} else {

 

Link to comment
https://forums.phpfreaks.com/topic/180650-clarification-on-forloop-working/
Share on other sites

The way a for loop works is fairly simple actually.

 

It's always of this form:

 

for (startStatement; condition; iterationStatement) {
    body
}

 

So when you start the for loop, the startStatement will be executed. Each time you do something in the loop is called an iteration and at the end of each iteration the iterationStatement will be executed. A new iteration will start as long as the condition evaluates to true. During an iteration, the body will be executed.

 

So doing something like this:

for ($i = 0; $i < 2; ++$i) {
    echo $i;
}

 

First you'll set $i = 0 and because 0 < 2 is true, we'll execute the body and print 0. Then we'll increment $i so now it holds the value 1. Because 1 < 2 is true, we'll execute the body again and so 1 is printed to the screen. Then $i is incremented again so it will hold the value 2. However, 2 < 2 is false, so the loop will terminate.

Just to extend on what Daniel0 said I want to clarify another thing. Alot of times newer programmers dont realize that arrays start at 0, so they in turn think that it is going to be 1 instead 0. So just make sure that you keep that in mind when you are using for loops. For example someone may try to loop through an array of 5 values to 5, but that wouldnt be correct because that would go through 6 values (0,1,2,3,4,5). just thought i would throw that out there.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.