In this tutorial, you shall learn how to convert an array into a CSV string using implode() function, with example programs.
PHP – Convert Array to CSV String
To convert a given array into a CSV (Comma Separated Value) string in PHP, use implode() String function. implode(separator, array)
returns a string with the elements or array
joined using specified separator
. So, if we pass comma character as argument for the separator
parameter, implode()
function returns CSV string of the elements in the array
.
Examples
1. Convert integer array to CSV string
In the following example, we take an array of numbers, and convert elements of this array to CSV String.
PHP Program
<?php
$arr = array(5, 2, 9, 1);
$output = implode(",", $arr);
printf("Output : %s", $output);
?>
Output
2. Convert string array to CSV string
In the following example, we take an array of strings, and convert elements of this array to CSV String.
PHP Program
<?php
$arr = array("apple", "banana", "cherry");
$output = implode(",", $arr);
printf("Output : %s", $output);
?>
Output
Conclusion
In this PHP Tutorial, we learned how to convert array into a CSV string, using implode()
function, with examples.