As Adam points out, it should work, though your starting index is wrong if you want to start at 1. Did you try it?
However, it
duplicates code by printing an <output> element in more than one place. You can avoid this by setting a variable to hold optional attributes.
PHP:
<select>
<?php for ($i=1; $i < $list_length; ++$i) {
if ($i === $selected) {
$attrs = 'selected';
} else {
$attrs = '';
}
?>
<option <?php echo $attrs ?>><?php echo $i ?></option>
<?php } ?>
</select>
(Note: if the value of an
option element is to be the same as its content, you can leave off the
value attribute. The value for an option element defaults to its text content.)
To avoid having to check for the selected option each time through the loop, assemble the document first, then set the selected option outside the loop. For example, you can do this with
SimpleXML:
PHP:
$doc = new SimpleXMLElement('<html />');
$select = $doc->addChild('select');
for ($i = 1; $i < $list_length; ++$i) {
$option = $select->addChild('option', $i);
}
$select->option[$selected-1]->addAttribute('selected','selected');
echo $select->asXML();
or with
DOM:
PHP:
$doc = new DOMDocument();
$select = $doc->createElement('select');
for ($i = 1; $i < $list_length; ++$i) {
$option = $doc->createElement('option', $i);
$select->appendChild($option);
}
$select->childNodes->item($selected-1)->setAttribute('selected', TRUE);
$doc->appendChild($select);
echo $doc->saveHTML();
There isn't much of a gain for any approach, so use whatever you wish. One potential advantage of the XML parsers (SimpleXML and DOM) is that you can define the structure for data in one place (
DRY, again) and process it for whatever purposes you need, such as creating forms or displaying data. It becomes very useful in an MVC architecture, as you can build up the document (or parts of the document), with different modules making changes as necessary until processing has finished.