Main | School

Dynamic PHP content

Many times When writing PHP code, you may not know exactly what needs to happen. For instance, when printing out an unknown number of items, or reading from a list on unkown length. While most other programming languages can easily deal with reading and writing dynamicly, to do this with PHP requires a few tricks.

For our example, take a PHP array that needs to be printed to the screen, along with a check box for the user to select. Normally, you would manualy write html code for each of the items in the list and use PHP code to fill in descriptive labeling. But what if the length of that list varies, and we need to create as many check boxes as there may be in the list? It would be very tedious to manualy made and remove html blocks every single time the list was chaanged. Fortunatly, there is an effective way to overcome this.

The key is in the PHP echo command. When echo prints something out onto the web page, it does so before the computer's browser has had a chance to interperet any html code. If the echo statement prints out html code for parts of a table, then the browser will display a much larger table than usual.
Example:


<?php
for ($i = 0; $i < $array.length(); $i = $i + 1){
   
   echo "<ul>";
   echo "<li>Array item: ".$array[$i]."</li>";
   echo "</ul>";
}
?>

This will create an unordered list that will have as many items in it as there are in the array. If The array was being passed by a session variable, or edited in another file and then included, we don't need to worry about the length of the list or size of the table.
Another Example:


<form action="< ?php $_SERVER['PHP_SELF'] ?>" method="post" id="frmcontact">

<?php

for ($i = 0; $i < $array.length(); $i = $i + 1){

    echo "<label for=\"txt\"".$i."\">Label</label><input type=\"text\" name=\"txt".$i."\" id=\"txt".$i."\" />";
}
?>
</form>

This is similar to the previous example, but it also adds a text field for every item in the array, and names it according to its place in the array. This way, a similar for loop can be made to read each of those text fields based on the same numbering system.

References: Blaine Robertson

Contact Me | Policies | Colophon

© 2009, Jonathan Dunstan, All Rights Reserved.