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.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net