PHP: Handle comma separated input

A quick example of how to handle comma separated input from a POST variable in PHP. The code below will turn your POST variable into an array containing the user’s input which you can further validate or store in a database. This is useful for letting users add tags to items on your website.

$tagsString = isset($_POST['tags']) ? (string)strip_tags($_POST['tags']) : '';
if ($tagsString != '') {
	$tags_array = explode(",", $tagsString);
	$tags_array = array_unique($tags_array); //no dups, please
	foreach($tags_array AS $key => $tag)
		$tag = trim(stripslashes($tag));
		if($tag == '') continue; //skips if empty
		echo $key.' - '.$tag;

, , ,