PHP Index

In order to become familiar with PHP programming structures and commands, we will build various PHP pages.S Sections of this page will explain each PHP command, provide a link to a working sample, and detail the working sample's PHP code. Let's get started:

For Loops

For loops allow the repeating of code for a set number of iterations (set number of times). You set a counter variable, condition for the counter, counter increment, and provide the code for a process.

Here's some code:

//set the counter variable, counter condition, and counter increment.
//counter variable: start the counter variable at zero
//condition: run the code (loop) while counter variable is less than 50
//counter increment: add one to the counter everytime you loop

for($counter=0 ; $counter<50; $counter=$counter+1)
{
echo "This is loop number ".$counter;
}

The above code starts the counter at zero, checks the condition, runs the code, then increments the counter variable. The code will continue looping until the counter variable evaluates to false. Code executions stops at that time.

Here's another example:forloops.php


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>forloops.php</title>
<style type="text/css">
table
{
margin:auto;
}
th
{
background-color:#FF9900;
border:1px solid black;
}
td
{
text-align:center;
border:1px solid black;
}
</style>
</head>
<body>

<table>
<tr><th>The following rows were created with a loop!</th></tr>
<?php

//set the counter variable, counter condition, and counter increment.
//counter variable: start the counter variable at zero
//condition: run the code (loop) while counter variable is less than 100
//counter increment: add one to the counter everytime you loop

for($counter=$counter <100$counter=$counter+1)

echo 
"<tr><td>";
echo 
"This is loop number ".$counter
echo 
"</td></tr>";

}
?>

</table>

</body>
</html>