Here is a slightly more general purpose solution. I was actually looking for a way to make row lists for bulk SQL inserts. The code will look like this:
foreach ($rows as $row) { $string = toDelimitedString($row);
And here is a useful function that I added to my takeit:
/** * Convert an array of strings to a delimited string. This function supports CSV as well as SQL output since * the quote character is customisable and the escaping behaviour is the same for CSV and SQL. * * Tests: * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '\'', true) . "\n"; * echo toDelimitedString(['A', 'B\'C'], ',', '\'', true) . "\n"; * echo toDelimitedString([], ',', '\'', true) . "\n"; * echo toDelimitedString(['A'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B'], ',', '"', true) . "\n"; * echo toDelimitedString(['A', 'B"C'], ',', '"', true) . "\n"; * * Outputs: * <Empty String> * 'A' * 'A','B' * 'A','B''C' * <Empty String> * "A" * "A","B" * "A","B""C" * * @param array $array A one-dimensional array of string literals * @param string $delimiter The character to separate string parts * @param string $quoteChar The optional quote character to surround strings with * @param bool $escape Flag to indicate whether instances of the quote character should be escaped * @return string */ function toDelimitedString(array $array, string $delimiter = ',', string $quoteChar = '"', bool $escape = true) { // Escape the quote character, since it is somewhat expensive it can be suppressed if ($escape && !empty($quoteChar)) { $array = str_replace($quoteChar, $quoteChar . $quoteChar, $array); } // Put quotes and commas between all the values $values = implode($array, $quoteChar . $delimiter . $quoteChar); // Put first and last quote around the list, but only if it is not empty if (strlen($values) > 0) { $values = $quoteChar . $values . $quoteChar; } return $values; }