explode() is not strpos() - [empty() is not broken]

Let's say that I worked on a recipe website.
The goal was to generate some HTML whenever we had one or more ingredients to show.
The data comes from a legacy MS-SQL server which returns a comma seperated list of ingredients.
When no ingredients are found, do not display the ingredient block and title.

I coded something like this:

  $ingredients = explode(',', $mssql_row['INGREDIENTS']);
  if (!empty($ingredients)) {
    $output .= theme('item_list', $ingredients, t('List of ingredients'));

PS: I was using Drupal, that is where theme() and t() comes from.

The problem was that no matter what, the block would always show up, with one item that shows nothing.
Basically, this HTML would get returned when I expected nothing at all:

  <div class="item-list">
    <h3>List of ingredients</h3>

I spent 30 minutes trying to debug this code. Trying to figure out why it was printing my list when it should not when the list is empty.
Was "empty()" broken? Surely not.

It turned out that I misunderstood what explode() was returning.

I presumed that if no comas were found, it would return an empty array.
I was wrong. It ended returning an array with one element: empty string

  $ingredients = array('');

The documentation clearly says:

If delimiter contains a value that is not contained in string, then explode() will return an array containing string.

Since my string was an empty string, that is exacly what got returned.

I fixed my code by doing:

  if (!empty($mssql_row['INGREDIENTS'])) {
    $ingredients = explode(',', $mssql_row['INGREDIENTS']);
    if (!empty($ingredients)) {
      $output .= theme('item_list', $ingredients, t('List of ingredients'));

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • You may post PHP code. You should include <?php ?> tags.
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options