Subscribe to RSS Feed

Code Snippets: Add comma’s to a string

↓ skip to article

Pretty commonly I’ll need to display a string of text that needs to be comma delineated using PHP.  This is the easiest way I have found to accomplish this.

<?php
$string = "test test2 test3 test4 test5 ";
echo substr(str_replace(" ", ", ", $string), 0, -2); //outputs test, test2, test3, test4, test5
?>

Make sure that there is a space added after every test or otherwise you’ll end up with the output test, test2, test3, test4, tes.

This could also be adapted into a function, if you wanted.

Tags: , ,

Comments (One comment)

Cool tip… simple and affective

Jeff / July 2nd, 2008, 11:51 am / #

Post a comment

Powered by WP Hashcash