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

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.