Home > Articles


  • Print
  • + Share This

3.2 Printing Out an Array

You want to print an entire array separated by commas.


Use PHP's implode() function to print out your list with commas as the separator:

$list = array ("Emily", "Jesse", "Franklin", "Chris");
print substr (implode (', ', $list), 0, -2);


The implode() function inserts a comma after every array element and returns a string with the inserted commas. We eliminate the last two characters of the string by using the substr() function because we do not need to print the trailing ', '. This is a very useful function for printing out entire arrays. In PHP, when you print $list; where $list is an array, PHP prints "array" instead of the elements of an array; therefore, implode() offers a shortcut for printing out an entire array.

If you want to print out an array without commas, you have two options. Here is the first and less-efficient way:

while ($i < count ($list) ) {
  print $list[$i++];

And here is the efficient way using implode():

print implode("", $list);

The first way of printing out an array loops through the array with a while loop, prints out the current item, and then increments to the next element. The second method strings the array elements one after another, separating them with an empty string.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.