views:

90

answers:

3

I am hacking together a theme for wordpress and I am 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?

A: 

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).

FrustratedWithFormsDesigner
Thanks for the quick reply. I must admit I don't know any php so a "copy pasteable" reply would be much appriciated :)
Thomas
@Thomas: But I'm sure you'll learn quickly!
FrustratedWithFormsDesigner
Every time this comes up people say to check for `len-1` and omit the final comma; am I the only person that checks for `0` and omits the first? It seems so much easier
Michael Mrozek
+6  A: 

Best way is with implode:

echo('<span>' . implode('</span>, <span>', $mykey_values) . '</span>');
AlexV
ah yes, I'd forgotten about `implode`! But does that cover the `<span>` tags?
FrustratedWithFormsDesigner
Yeah implode is so nice for that :) Updated answer to include the span now.
AlexV
Wouldn't you want `implode('</span>, <span>', $vals)` instead? That way, each value is in a span tag. That's what the OP seems to be doing in the code in question... Just a thought. =)
Jeff Rupert
<?php $mykey_values = get_post_custom_values('services'); foreach ( $mykey_values as $key => $value ) { echo('<span>' . implode(', ', $mykey_values) . '</span>'); } ?>gives me: Redesign, Nyhedsbrev, Fotografi, DesignRedesign, Nyhedsbrev, Fotografi, DesignRedesign, Nyhedsbrev, Fotografi, DesignRedesign, Nyhedsbrev, Fotografi, desired output would be: Redesign, Nyhedsbrev, Fotografi
Thomas
ah I got it - the foreach messed it up. This solved it <?php $mykey_values = get_post_custom_values('services'); { echo('<span>' . implode(', ', $mykey_values) . '</span>'); } ?>Thanks a bunch - you guys rock
Thomas
@Jeff Rupert: Yes indeed! Updated my answer :)
AlexV
=) You're welcome!
Jeff Rupert
For the record, the fastest means of running this code would be: `echo '<span>' , implode('</span>, <span>', $mykey_values) , '</span>';` as the commas prevent PHP from performing unnecessary computation and the parenthesis are unnecessary.
mattbasta
A: 
echo "<span>" . implode(',</span><span>',$mykey_values) . "</span>;

Edit: BTW, you don't use the loop if you use this code.

Fletcher Moore