4.9. Turning an Array into a String4.9.2. SolutionUse join( ):
Or loop yourself:
4.9.3. DiscussionIf you can use join( ), do; it's faster than any PHP-based loop. However, join( ) isn't very flexible. First, it places a delimiter only between elements, not around them. To wrap elements inside HTML bold tags and separate them with commas, do this:
Second, join( ) doesn't allow you to discriminate against values. If you want to include a subset of entries, you need to loop yourself:
Notice that a separator is always added to each value, then stripped off outside the loop. While it's somewhat wasteful to add something that will be later subtracted, it's far cleaner and efficient (in most cases) then attempting to embed logic inside of the loop. To wit:
Now you have to check $string every time you append a value. That's worse than the simple substr( ) call. Also, prepend the delimiter (in this case a comma) instead of appending it because it's faster to shorten a string from the front than the rear. 4.9.4. See AlsoRecipe 4.10 for printing an array with commas; documentation on join( ) at http://www.php.net/join and substr( ) at http://www.php.net/substr.
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|