- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
3.2 Printing Out an Array
You want to print an entire array separated by commas.
Technique
Use PHP's implode() function to print out your list with commas as the separator:
<?php $list = array ("Emily", "Jesse", "Franklin", "Chris"); print substr (implode (', ', $list), 0, -2); ?>
Comments
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:
<?php while ($i < count ($list) ) { print $list[$i++]; } ?>
And here is the efficient way using implode():
<?php 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.