Using PHP’s implode() Function to Display an Array as a Value-Separated String

When displaying the contents of an array in PHP, what is your go to method? For example, if the items need to be displayed as a comma-separated or HTML unordered list, would you use a foreach() or for() loop? Utilizing a loop would accomplish the task. But there are other options. Why not give the implode() function a shot.

Let's say we have an array of our customer's favorite movies.

<?php
$movies_to_display = array('Star Wars', 'Book of Eli', 'Avatar', 'Star Trek', 'Matrix');
?>

To display the movies as a comma-separated list, we might utilize a foreach() loop.

<?php
print '<div>';
foreach($movies_to_display as $curr_movie) {
     print "$curr_movie, ";
}
print '</div>';
?>

But that displays an extra comma at the end of the list. One way to avoid the unwanted character is to use a for() loop instead.

<?php
print '<div>';
for($i=0; $i < count($movies_to_display); $i++) {
     print ($i==0) ? $movies_to_display[$i] : ", $movies_to_display[$i]";
}
print '</div>';
?>

The first time through the loop (when $i equals zero), only the current value is displayed. Otherwise it displays a comma, space, and then the value. Now the list is displayed without the extra comma.

Note that the above code uses the Ternary Operator (?:) instead of the standard if/else structure. For more information about how the operator works, check out my previous post titled "Utilizing the Short-hand if() within a PHP String."

Using implode() Instead

As with most things in PHP, there are many other solutions which involve looping constructs like foreach(), while(), etc. However, there is a more efficient way. Unless the loop is doing more than displaying the list, we could use implode() instead.

<?php
print '<div>' . implode(', ', $movies_to_display) . '</div>';
?>

The first argument of the implode() function determines what's added between each array value. So what if we need to display the values as an HTML list? Well that's pretty easy to do with a little extra code before and after the implode().

<?php
print '<ul><li>' . implode('</li><li>', $movies_to_display) . '</li></ul>';
?>

Conclusion

Although loops can be modified to display the data as we want, there are alternatives which may be better to suited for our needs. Displaying an array of items separated by some character(s) is one of those times. So save yourself a few lines of code and implode() the array instead.

1 Comment

  • #1 Asanka on 03.28.15 at 7:28 am

    This article just saved my day

Leave a Comment