PHP Implode But Wrap Each Element In Quotes

Add the quotes into the implode call: (I'm assuming you meant implode)

$SQL = 'DELETE FROM elements
           WHERE id IN ("' . implode('", "', $elements) . '")';

This produces:

DELETE FROM elements WHERE id IN ("foo", "bar", "tar", "dar")

The best way to prevent against SQL injection is to make sure your elements are properly escaped.

An easy thing to do that should work (but I haven't tested it) is to use either array_map or array_walk, and escape every parameter, like so:

$elements = array();
$elements = array_map( 'mysql_real_escape_string', $elements);

You can use array_walk to iterate all the elements in side the array passing the reference to the element and add the quotes in the following way.

php 7.4 or newer

<?php

$arr = ['a','b','c'];

array_walk($arr, fn(&$x) => $x = "'$x'");

echo implode(',', $arr); // 'a','b','c'

php 7.3 or older version

<?php

$arr = ['a','b','c'];

array_walk($arr, function(&$x) {$x = "'$x'";});

echo implode(',', $arr); // 'a','b','c'

How about json_encode?

$arr=array("foo","bar","tar","dar");
$str=json_encode($arr);
echo $str;

Result: ["foo","bar","tar","dar"]


You can run a simple array_map() function to wrap the strings in quotes and then wrap that around the implode() to add the commas:

$array = ["one", "two", "three", "four"];

implode(",", array_map(function($string) {
    return '"' . $string . '"';
}, $array));

Tags:

Php

Implode