PHP loops
Written by Administrator   
Friday, 12 March 2010
Article Index
PHP loops
The For loop
A practical example

Example

It is always difficult to find example of the use of such basic facilities as if statements and loops because they really only come into their own when you have enough PHP to need them. However the task of generating an HTML table is a good and realistic use of a loop.

An HTML table, in case you have forgotten, is simply a set of rows and columns - i.e. it really is a table. To create a table you start off with a pair of <TABLE></TABLE> tags. Each row of the table corresponds to a pair of  <TR></TR>  tags and each cell within the row corresponds to a pair of <TD></TD> tags. For example:

<TABLE>
<TR>
<TD>first cell</TD>
<TD>second cell</TD>
</TR>
</TABLE>

creates a table with one row and two cells.

To make the rows and cells more obvious we can set the border attribute in the <TABLE> tag say <TABLE border=1>. With this change the table looks like:

table1

Now imagine you need to create a table for some with a single row but a variable number of cells. The most natural way of doing this is to use a for loop. For example:

echo("<TABLE border=1><TR>");
for($i=1;$i<=10;$i++){
    echo("<TD> Cell " . $i . "</TD>");
}
echo("</TR></TABLE>");

This first sends the table tags needed to start the first row to the web page. Then the for loop generates ten cells each suitably labeled using the index and finally the closing row and table tags are sent to the web page. The resulting HTML generated by the small program is:

<TABLE border=1><TR>
<TD> Cell 1</TD>
<TD> Cell 2</TD>
<TD> Cell 3</TD>
...
<TD> Cell 9</TD>
<TD> Cell 10</TD>
</TR></TABLE>

notice that it isn't formatted to be easy to read but then HTML doesn't have to be and it still works.

When viewed in a browser the page looks like:

table2

You can probably guess that it isn't difficult to write a loop that generates more than a single row. This is the power of PHP - it can generate HTML that would take you a long time to do by hand.

 

Banner


PHP Inner Functions And Closure

PHP inner functions and anonymous functions are a little strange to say the least. However, just because something is strange doesn't mean that it isn't useful. We take a close look at the way PHP fun [ ... ]



Ten minutes To PHP Objects

PHP is a fully object-oriented language with lots of powerful features. This introductory guide looks at how PHP handles objects.


Other Articles

<ASIN:0470563125>

<ASIN:0596157134>

<ASIN:0596006810>

 

$a=1000;
do{
    echo($a .'<br/>');
    $a=$a/10;
}while($a>1)


Last Updated ( Monday, 15 March 2010 )