Take the 2-minute tour ×

As I'm a bit of php noob, I'm not sure whether to go with preg_replace() or to explode() then implode(). Either way, I don't know how to go about it.

I'm in wordpress, and I'm running this code:

<?php $terms = wp_get_post_terms($post->ID,'jobtype');
foreach($terms as $term){echo ', ' . $term->name;} ?>

I need to capture into a string the echo ', ' . $term->name; and remove that first ', '.

Even if there's a different way I can echo the term names, could you guys (and gals) help me out?


share|improve this question
you want to replace the first ',' by what ? –  yokoloko Aug 5 '11 at 21:28
@yokoloko If you look at the topic, I just want to remove it. –  Josh Allen Aug 5 '11 at 21:32
add comment

1 Answer

up vote 3 down vote accepted

Old school:

$names = array();
foreach($terms as $term){
    $names[] = $term->name;
echo implode(',', $names);

As PHP 5.3 introduced anonymous functions [docs], array_map [docs] becomes more interesting for these "one time" jobs:

echo implode(',', array_map(function($term) { return $term->name; }, 

Or maybe more descriptive with a reusable function:

function getProperty($prop) {
    return function($object) use ($prop) {
        return $object->{$prop};

echo implode(',', array_map(getProperty('name'), 

But as said, this only works if you use PHP 5.3.

share|improve this answer
This works perfectly! I'm not in the mood to look if my host supports PHP 5.3, so I'll just use what works. Thanks so much! –  Josh Allen Aug 5 '11 at 21:34
@JoshAllen: You're welcome :) –  Felix Kling Aug 5 '11 at 21:35
add comment

Your Answer


