Search code examples
phpstringdelimiterquote

PHP adding single quotes to comma separated string


I know I have done this before. I am not sure why I am struggling to do something so simple.

All I am trying to do is add a single quote to a comma separated string.

The php process initially looks like this:

<?php
  $checknumber = mysqli_real_escape_string($dbc,trim($_POST['checknumber']));

 $splitnumber = preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$checknumber )));

 $numbers = "'" . implode("', '", $splitnumber ) ."'";

 echo $checknumber;
 echo $splitnumber;
 echo $numbers;
?>

The results look like this:

// $checknumber
AMD111111,AMD222222,AMD333333

// $splitnumber
AMD111111,AMD222222,AMD333333

// $numbers
''

I need the results of $numbers to look like this:

'AMD111111','AMD222222','AMD333333'

The funny thing is I am using a piece of code I've used before that works. So I am at a loss as to why the code is not working here.


Solution

  • The implode() function requires an array as second argument. It looks like your $splitnumber is just a simple string not an array of strings as it should probably be. Try splitting your $splitnumber by commas using the explode() function and put the result of that in the implode function.

    Should look like that (not tested):

    $splitnumber = ...;
    $splittedNumbers = explode(",", $splitnumber);
    $numbers = "'" . implode("', '", $splittedNumbers) ."'";
    

    There is probably a cleaner solution by just replacing all occurences of , with ','.