[eluser]SitesByJoe[/eluser]
I just finished this function I needed to handle yanked csv values from database fields and thought I'd share with you. I've added this to my HTML_helper but you can put it anywhere you prefer.
Code:
function csv_to_nice_string($csv)
{
$str = ''; // an empty string to build on
$csv = explode(',', $csv); // make an array of our string
$total = count($csv); // count the elements
$array_total = ($total - 1); // the array total (uses 0 index)
if ($total > 1)
{
if ($total == 2)
{
// only two items so just switch the comma for an AND
$str = implode(' and ', $csv);
}
else
{
// there are more than 2 entries
for ($i = 0; $i < $array_total; $i++)
{
$str .= $csv[$i] . ', ';
}
// add the "and" last
$str .= ' and ' . $csv[$array_total];
// fix the last comma if necessary
$str = str_replace(', and', ' and ', $str);
}
}
else
{
// only one item so just return string
$str = $csv[0];
}
// finally, return the string we made
return $str;
}
Let me know if you see anything that could be improved. Hopefully it'll prove helpful to someone else.