Empty Lists

We have all written this code before :

<ul>
  <?php foreach ($list as $element):?>
    <li><?=htmlspecialchars($element)?></li>
  <?php endforeach; ?>
</ul>

What happens when the list is empty? What is generated is an empty UL element :

<ul></ul>

This would be perfectly fine, if it wasn’t completely wrong. Quoth the XHTML DTDs (any of them) :

<!ELEMENT ul (li)+>

There must always be at least one list item in a list (what kind of insanity would have led to preventing empty lists from existing is beyond me, although I’m certain they must have had a good reason), which means a document will not validate if it contains the aforementioned empty UL element. This is also the case for HTML 4, though HTML 5 does currently allow empty lists.

So, to circumvent the empty list case, the code becomes:

<?php if (count($list) > 0): ?>
  <ul>
    <?php foreach ($list as $element): ?>
      <li><?=htmlspecialchars($element)?></li>
    <?php endforeach; ?>
  </ul>
<?php endif; ?>

While it might be possible to abstract these details away behind a function that prints a list of elements, the ultimate point of such an abstraction would be to free the developer’s mind of the issue of empty lists not being allowed in XHTML. And such a thing would be ill advised : since the correct behavior is to remove the empty list from the document, the developer should be aware that no UL element will be generated for an empty list, especially since this has implications on the CSS side (which has to accomodate the absence of the list) and the Javascript side (which has to create the element if it doesn’t exist before adding elements to it).

An important quality of any developer is their ability to identify and handle any corner cases of their domain. An important quality of any domain is to have as few corner cases as possible.

1 Responses to “Empty Lists”


  1. No Comments
  1. 1 Best Practices at Nicollet.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



706 feed subscribers
(readers who polled a feed this week)