Arrays and HTML

Arrays are great because they’re used to hold lists of data in your programming
language. Of course, HTML already has other ways of working with
lists. The <ul> and <ol> tags are both used for visual representations of
lists, and the <select> object is used to let the user choose from a list. It’s
very common to build these HTML structures from arrays.



The code for the page is not too different than the previous examples. It just
adds some HTML formatting:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/
xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>arrayHTML.php</title>
<meta http-equiv=”Content-Type” content=”text/html;charset=UTF-8” />
</head>
<body>
<h1>Arrays are useful in HTML</h1>
<div>
<?php
//first make an array of mini-book names
$books = array(”Creating the XHTML Foundation”,
”Styling with CSS”,
”Using Positional CSS for Layout”,
”Client-Side Programming with JavaScript”,
”Server-Side Programming with PHP”,
”Databases with MySQL”,
”Into the Future with AJAX”,
”Moving From Pages to Web Sites”);

//make the array into a numbered list
print ”<ol>\n”;

foreach ($books as $book){
print ” <li>$book</li> \n”;
} // end foreach
print ”</ol>\n”;
//make the array into a select object
print ”<select name = \”book\”> \n”;
foreach ($books as $book){
print ” <option value = \”$book\”>$book</option> \n”;
} // end foreach
print ”</select> \n”;
?>
</div>
</body>
</html>

It’s a relatively simple matter to build HTML output based on arrays. To
create an ordered list or unordered list, just use a foreach loop but add
HTML formatting to convert the array to a list formatted in HTML:
//make the array into a numbered list
print “<ol>\n”;
foreach ($books as $book){
print “ <li>$book</li> \n”;
} // end foreach
print “</ol>\n”;