Comma seperated values from array

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
User avatar
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm

Comma seperated values from array

Post by onion2k »

Someone on a different forum I frequent asked for some code to create a comma seperated list of the values in an associated array, without using the empty entries.

The obvious solution that was first suggested was to iterate around a loop checking each of the array values and concatenating it into a string. But I came up with this rather elegant solution:

Code: Select all

function not_empty($e){ return !empty($e); }
$string = implode(",",array_filter($array,"not_empty"));
Just thought I'd share. I'd prefer to define not_empty as an anonymous function, but array_filter doesn't like using them as a callback for some reason.

NB: What's up with the tags? They're not working.
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

I'm working on it - should be restored in an hour or two.
Post Reply