Welcome Guest, Not a member yet? Register   Sign In
Change a CSV string into a nice, readable string
#1

[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.
#2

[eluser]Unknown[/eluser]
Hi,

This is exactly what I need to list tags that are added by comma separation. I fairly new to Code Ignitor, could you possible show me how you could implement that in the controller and view files.

Any feedback would be grateful.




Theme © iAndrew 2016 - Forum software by © MyBB