[php] php implode (101) with quotes

Imploding a simple array

would look like this

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

and that would return this

 lastname,email,phone

great, so i might do this instead

$array = array('lastname', 'email', 'phone');
$comma_separated = implode("','", $array);
$comma_separated = "'".$comma_separated."'";

and now i have what I want a nice pretty csv string

 'lastname','email','phone'

is there a better way to do this, it feels to me like there should be an optional parameter for implode am I missing something ?

This question is related to php arrays string csv implode

The answer is


$array = array('lastname', 'email', 'phone');


echo "'" . implode("','", $array) . "'";

$ids = sprintf("'%s'", implode("','", $ids ) );

Don't forget to escape your data! If you want to put data in a CSV file without fputcsv function or put it in a SQL query use this code:

$comma_separated = "'" . implode("','", array_map('addslashes', $array)) . "'";

This code avoids SQL injection or data fragmentation when input array contains single quotation or backslash characters.


Don't know if it's quicker, but, you could save a line of code with your method:

From

$array = array('lastname', 'email', 'phone');
$comma_separated = implode("','", $array);
$comma_separated = "'".$comma_separated."'";

To:

$array = array('lastname', 'email', 'phone');
$comma_separated = "'".implode("','", $array)."'";

You could use array_map():

function add_quotes($str) {
    return sprintf("'%s'", $str);
}

$csv =  implode(',', array_map('add_quotes', $array));

DEMO

Also note that there is fputcsv if you want to write to a file.


If you want to use loops you can also do:

$array = array('lastname', 'email', 'phone');
foreach($array as &$value){
   $value = "'$value'";
}
$comma_separated = implode(",", $array);

Demo: http://codepad.org/O2kB4fRo


you can do it this way also

<?php
$csv= '\'' . join(array('lastname', 'email', 'phone'),'\',').'\'';
echo $csv;
?>

$id = array(2222,3333,4444,5555,6666);
$ids = "'".implode("','",$id)."'";

Or

$ids = sprintf("'%s'", implode("','", $id ) );

Alternatively you can create such a function:

function implode_with_quotes(array $data)
{
    return sprintf("'%s'", implode("', '", $data));
}

Another possible option, depending on what you need the array for:

$array = array('lastname', 'email', 'phone');
echo json_encode($array);

This will put '[' and ']' around the string, which you may or may not want.


If you want to avoid the fopen/fputcsv sub-systems here's a snippet that builds an escaped CSV string from an associative array....

$output = '';
foreach ($list as $row) {
  $output .= '"' . implode('", "', array_values($row)) . '"' . "\r\n";
}

Or from a list of objects...

foreach ($list as $obj) {
  $output .= '"' . implode('", "', array_values((array) $obj)) . '"' . "\r\n";
}

Then you can output the string as desired.


I think this is what you are trying to do

$array = array('lastname', 'email', 'phone');
echo "'" . implode("','", explode(',', $array)) . "'";

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to csv

Pandas: ValueError: cannot convert float NaN to integer Export result set on Dbeaver to CSV Convert txt to csv python script How to import an Excel file into SQL Server? "CSV file does not exist" for a filename with embedded quotes Save Dataframe to csv directly to s3 Python Data-frame Object has no Attribute (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape How to write to a CSV line by line? How to check encoding of a CSV file

Examples related to implode

Return single column from a multi-dimensional array How to implode array with key and value without foreach in PHP php implode (101) with quotes Implode an array with JavaScript? Fastest way to implode an associative array with keys