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"
If you enjoyed this article, please share it with a friend!

One Response to Convert Array Elements To CSV Format

  1. Geo says:

    Two shortcuts you’re missing:

    you can use foreach($array as $i => $element)

    and you can use implode() to stick the commas in.