Convert Array Elements To CSV Format

The following code will convert a PHP array into CSV format.

Code

// Converts array elements to a CSV string
function csv($array) {
    $csv = "";
    for( $i = 0; $i < count($array); $i++ ) {
        $csv .= '"' . str_replace('"', '""', $array[$i]) . '"';
        if( $i < count($array) - 1 ) $csv .= ",";
    }
    return $csv;
}

Output

$a = array("item 1", "item 2", "item 3");

echo csv($a); // Output: "item 1","item 2","item 3"
Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.