Rookie PHP question

I am a hack for a wordpress theme and I am using the following code to output data from a custom field with multiple values:

            <?php  $mykey_values = get_post_custom_values('services');
            foreach ( $mykey_values as $key => $value ) {
            echo "<span>$value, </span>";
            } ?>

      

I use a comma to separate the results, but I don't want a comma after the last result. How do I get around this?

+2


a source to share


3 answers


The best way is implode :



echo('<span>' . implode('</span>, <span>', $mykey_values) . '</span>');

      

+6


a source


There are many ways to do this ... the first one I can think of, instead of using echo, concatenate all the results into a string and then remove the last character ,

.



Another way would be to use a loop for

instead foreach

and then iterate up to size $mykey_values

- 1 and then print the last one without ,

. And I'm sure others will post other ways (maybe with real code too - my PHP is too rusty for me to risk real code sample).

0


a source


echo "<span>" . implode(',</span><span>',$mykey_values) . "</span>;

      

Edit: BTW, you are not using a loop if you use this code.

0


a source







All Articles