Robert Andrews Robert Andrews - 8 months ago 39
PHP Question

How to insert comma separation when there are multiple values?

I have this function...

* Just a private function to
* populate column content
private function lh_user_taxonomies_get_user_taxonomies($user, $taxonomy, $page = null) {
$terms = wp_get_object_terms( $user, $taxonomy);
if(empty($terms)) { return false; }
$in = array();
foreach($terms as $term) {
$href = empty($page) ? add_query_arg(array($taxonomy => $term->slug), admin_url('users.php')) : add_query_arg(array('user-group' => $term->slug), $page);
$in[] = sprintf('%s%s%s', '<a href="'.$href.'" title="'.esc_attr($term->description).'">', $term->name, '</a>');
return implode('', $in);

It outputs a list of taxonomy terms in WordPress to which an object is attached.

The problem is, as written, the function echoes out the values with no separation between multiple values, eg. "Financial ServicesInformation Technology" in HTML anchors.

I would like to insert logic such that, when there is more than one value, comma-and-space separation is used, eg. "Financial Services, Information Technology". But, of course, this should not happen when the value is the final value output.

How can I modify this to achieve it?

Answer Source

Change this line: return implode('', $in);

To this: return implode(', ', $in);

This should concatenate them all together, but with a comma and a space between them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download