There are 3 types of loop in PHP:
while (condition)
{ code_goes_here; }
do
{ code_goes_here; }
while (condition);
for(expr1, expr2, expr3)
{ code_goes_here; }
In terms of the ‘for’ loop above, ‘expr1′ being the starting expression, i.e. $i=0. expr2 being the condition that must be satisfied to keep the loop running, i.e. $i < 100. expr3 being the expression evaluated each time the loop runs, i.e. $i++. Each loop type has it’s uses.
The two while loops are mostly identical, the only difference being that in the first loop, the condition is checked before running that iteration of the loop whereas in the second loop, the condition is checked after running the loop iteration. The while loop will exit as soon as any negative condition such as a 0, FALSE, etc is hit. That makes it useful for fetching mysql result sets for example:
while ($result = mysql_fetch_assoc($resource))
{ //execute code using $result variable }
As opposed to:
$num = mysql_numrows($resource);
for ($ctr = 0; $ctr < $num; $ctr++)
{
$result = mysql_fetch_assoc($resource));
}
Additionally, the for loop does have advantages in cases, such as:
for ($ctr = 0; $ctr < 10; $ctr++)
{
echo “Counter is: ” . $ctr;
}
As opposed to:
while ($ctr < 10)
{
echo “Counter is: ” . $ctr;
$ctr++;
}
Although in this case there isn’t a great deal of difference. Just remember when looping through database results for example not to call functions or otherwise incur overhead in the loop such as calling mysql_numrows($result) unnecessarily.
Tags: do, for, loop, MySQL, PHP, PHP Developer, PHP MySQL Developer
You must be logged in to post a comment.
PHP basics never turns grey! You made it still shinny adam. Kudos!