php implode (101) with quotes - php

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 ?

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

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

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.

No, the way that you're doing it is just fine. implode() only takes 1-2 parameters (if you just supply an array, it joins the pieces by an empty string).

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)."'";

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

$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));
}

try this code :
$data = 'ABC,DEF,GHI';
$str = "'".str_replace(',',"','",$data)."'";
echo $str;

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.

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.

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.

Another solution is achieved using implode + preg_replace as follows:
$a = ['A', 'B', 'C'];
implode(',', preg_replace('/^(.*)$/', '"$1"', $a)); // "A","B","C"
$b = [];
implode(',', preg_replace('/^(.*)$/', '"$1"', $b)); // empty string
As you can see this also saves you from checking if the array is empty.

you can do it this way also
<?php
$csv= '\'' . join(array('lastname', 'email', 'phone'),'\',').'\'';
echo $csv;
?>

I think this is what you are trying to do
$array = array('lastname', 'email', 'phone');
echo "'" . implode("','", explode(',', $array)) . "'";

Related

arraymap vs foreach loop when creating a comma delimited string

I'm creating a comma delimited string for an SQL query. I would like to know what is better arraymap or a foreach loop. Here are my two examples:
$group_ids = "";
foreach ($group_array as $group_id) {
$group_ids .= $group_id . ",";
}
$group_ids = rtrim($group_ids, ',');
vs
$group_ids = "";
array_map(function ($group_id) use ($group_ids) {
$group_ids .= $group_id . ",";
return;
}, $group_array);
$group_ids = rtrim($group_ids, ',');
Or is there a better way? Or is there literally not much difference?
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
from
http://php.net/manual/en/function.implode.php
would be more efficient
You can also use implode(',',$array_of_ids). Just make sure you trim your values before using the implode.
$ids = ['foo','bar','boo'];
$ids = array_map('trim',$ids);
$ids_list = implode(',',$ids);
echo $ids_list; # foo,bar,boo

How to generate a WHERE clause from an array with multiple AND-conditions

I have an HTML-table, where various selections can be made. The selected variables that contain the respective values, build the array $data[]. Now, with this array I would like to make an SQL request where all selected criteria should be met. This means, that I need the following request:
SELECT * FROM fruitgroups
WHERE $selection[1] = $value[1]
AND $selection[2] = $value[2]
AND $selection[3] = $value[3]
etc ...
Can anybody please help me with the loop that generates exactly the string:
...
$selection[1] = $value[1]
AND $selection[2] = $value[2]
AND $selection[3] = $value[3]
... etc ...
...that I need for the request?
Thank you in advance!
You can make a SQL request like this:
$selection = array("one", "two", "three");
$value = array("Tone", "Ttwo", "Tthree");
$concat = array();
foreach($selection as $key => $var){
$new = $selection[$key] . " = " . $value[$key];
array_push($concat, $new);
}
$concat = implode(" AND ", $concat);
$request = 'SELECT * FROM fruitgroups WHERE ' . $concat . ';';
echo $request;
Run example
Similar to the answer above, but keep it simple and don't forget the single quotes around the values:
$clauses = [];
foreach ($values as $i => $value) {
$conditions[] = "{$selection[$i]} = '$value'";
}
$query = "SELECT * FROM fruitgroups WHERE " . implode(' AND ', $conditions);
Even better, use an ORM like Eloquent:
$conditions = [];
foreach ($values as $i => $value) {
$conditions[$i] = $value;
}
$result = App\FruitGroups::where($conditions)->get();
I'm assuming you are sanitizing your inputs first, of course.

how to add Apostrophe in php native

I have a following string
$data = "20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209";
How to add ' in $data. So the resultant output is as follows
'20150825131738_262','20150825132227_241','20150825132254_898','20150825132320_209,20150825132346_124','20150825132406_744','20150825143522_447','20150828145011_928'
help me thank's
Following would give you the desired results
$data = "20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209";
$data_array = explode(',', $data);
$data = "'". implode("','", $data_array) . "'";
print_r($data);
See it running online here
Try This
$arr=explode(',', $data);
implode("','",$arr);
If you are getting this value from database or some other sources then you can simply use one of these ways using simple implode and explode function as
$data = "20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209";
echo "'".implode("','",explode(',',$data))."'";
or using preg_replace_callback as
$data = "20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209";
echo preg_replace_callback('/[\d_]+/',function($match){ return "'$match[0]'";},$data);
$data = "20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209";
$pad_data = "'" . $data . "'";
$data = str_replace (",", "', '", $pad_data);
echo $data;
A slightly different method from the other answers:
$data = '20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209';
# Split data into individual fields
$array = explode(',', $data);
# Surround each field with single quotes
$array = array_map(
function ($field) { return "'${field}'"; },
$array
);
# Join fields back into a single string again
$data = implode(',', $array);
echo $data;
The code can be seen running here.

PHP explode array with 2 types of separators

I have this options array:
string(111) "colors:black;white;transparent;pink;"
how can I explode it so I get as a label first separator : and the rest in array as options? I have this so far:
$options= explode(";",$rows[0]);
$htm= '<ul class="product_opts">'.$lang['available_options'].'';
foreach ($options as $value) {
$row=mysql_fetch_row($result);
$htm.='<li style="text-align:left;font-weight:normal;">'.$value.'</li>';
}
$htm.= '</ul>';
}
echo $htm;
but it returns the label as option too..
$attributes="colors:black;white;transparent;pink;";
list($attribute, $values) = array_map(
function($value) {
return array_filter(explode(';', $value));
},
explode(':', $attributes)
);
var_dump($attribute);
var_dump($values);
$str = "colors:black;white;transparent;pink;";
list($label, $optionsStr) = explode(":", $str);
$optionsStr = rtrim($optionsStr, ";");
$options = explode(";", $optionsStr);
echo "<pre>";
print_r($label);
print_r($options);
Explode string by :. First token will be your label, second token your options.
Explode second token by ;, and you have your options in an array.
Try
$str = "colors:black;white;transparent;pink;";
$arr = explode(";",$str);
$key = explode(":",$arr[0]);
$arr[0] = $key[1];
unset($arr[sizeof($arr)-1]);
See demo here
use split to do like so
$options= split("[;|:]",$rows[0]);

Concatenation of string with a specific array elements

the given code below insert data from an array to the mysql table.as its not the full code but what i want to know is available in this code. my question is that there is a field in table named "image_url" but the data in that field only have image name and i want to append http://www.xxxxxx.com at the start of every image name and the replace it with the image name in the field but i dont know how to do that plz help me out
thanks in advance
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (".implode(',',array_keys($v)).") VALUES ('".implode("','",$v)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}
This snippet should do what you want:
if (isset($v['image_url'])) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
}
You can concatenate strings with the dot "."!
At first... Is your application protected against SQL injection? If not you should build two methods/functions like this using mysql_real_escape_string():
function sqlSafeKey( $key){
return '`' . mysql_real_escape_string( $key) . `'`;
}
function sqlSafeValue( $value){
return "'" . mysql_real_escape_string( $value) . "'";
}
And than use array_map() to escape your values like this:
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
About your question... The matzino's answer is correct and whole loop should look like this:
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
$query = "INSERT INTO test (".implode(',', $keys).
") VALUES ('".implode("','",$values)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}

Categories