Rookie PHP question
I am hacking together a theme for wordpress and I a开发者_运维知识库m using the following code to pull out data from a custom field with several values:
<?php $mykey_values = get_post_custom_values('services');
foreach ( $mykey_values as $key => $value ) {
echo "<span>$value, </span>";
} ?>
I use a comma to seperate the results, but I don't want a comma after the last result. How do I get around this?
Best way is with implode:
echo('<span>' . implode('</span>, <span>', $mykey_values) . '</span>');
Many ways to do this... the first one I can think of is instead of using echo, concatenate all the results into a string, then remove the last ,
character.
Another way would be to use a for
loop instead of foreach
and then iterate to the size of $mykey_values
- 1 and then print the last one without a ,
. And I'm sure others will post other ways (maybe with real code too - my PHP is too rusty for me to risk a real code sample).
echo "<span>" . implode(',</span><span>',$mykey_values) . "</span>;
Edit: BTW, you don't use the loop if you use this code.
精彩评论