-2

I'm having a problem in imploding an array to comma separated with double quotation. My Script is as below:

<?php

$arr = array(1,2,3,4,5,6,7,8,9);

$string = rtrim(implode('", ', $arr), ',');

echo $string; 

The output is:

1", 2", 3", 4", 5", 6", 7", 8", 9

But I want this output below:

"1", "2", "3", "4", "5", "6", "7", "8", "9"

So anyone can help me with this problem please?

Thanks!

6
  • I smell a bigger problem… where are you going to use this imploded string exactly?
    – deceze
    Commented Sep 7, 2016 at 7:56
  • 2
    $string = '"' . implode('", "', $arr) . '"';, this would solve it, but why would you need such output?
    – user1897253
    Commented Sep 7, 2016 at 7:57
  • @deceze i am want to make a IPs output for a project that should be return like : '162.251.82.122', '162.251.82.250', '162.251.82.123', '162.251.82.251'
    – Shiv Singh
    Commented Sep 7, 2016 at 8:00
  • And why does your "project" need a string in this particular format? Can't you use proper serialisation, e.g. JSON?
    – deceze
    Commented Sep 7, 2016 at 8:01
  • @deceze Its a NET_DNS2 out put of A records of a host name and client want to display as i have provided.
    – Shiv Singh
    Commented Sep 7, 2016 at 8:13

4 Answers 4

3

I'll just throw this into the ring as alternative solution:

$string = trim(json_encode(array_map('strval', $arr)), '[]');

json_encode produces the desired result, just wrapped in a [..]; simply trim off the brackets.

3
  • (Because, who can resist a bike-shed question, right?)
    – deceze
    Commented Sep 7, 2016 at 8:21
  • its not showing output as i am want check demo: ideone.com/oRHeFv
    – Shiv Singh
    Commented Sep 7, 2016 at 8:27
  • LOL, yup, it doesn't. ^_^;; You need to convert your values to strings… fixed it.
    – deceze
    Commented Sep 7, 2016 at 8:31
1

try this,

$arr = array(1,2,3,4,5,6,7,8,9);    
$string = implode('", "', $arr);   
$string =  '"'.$string.'"';
echo $string;

OUTPUT :

"1", "2", "3", "4", "5", "6", "7", "8", "9"

DEMO

0
-1

You should have added the Opening and Closing Closing Double Quotes and No Need for the rtrim. The Following Code which you may test Here would do:

<?php

    $arr    = array(1,2,3,4,5,6,7,8,9);
    $string = '"' . implode('", "', $arr) .'"';

    echo $string;
0
-2

its work for you

 $arr    = array(1,2,3,4,5,6,7,8,9);
 $string = '"'.implode('", "', $arr).'"';

echo $string;
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.