-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!

Brewology
  • 108
  • 2
  • 15
Shiv Singh
  • 6,939
  • 3
  • 40
  • 50
  • I smell a bigger problem… where are you going to use this imploded string exactly? – deceze Sep 07 '16 at 07:56
  • 2
    `$string = '"' . implode('", "', $arr) . '"';`, this would solve it, but why would you need such output? –  Sep 07 '16 at 07: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 Sep 07 '16 at 08:00
  • And why does your "project" need a string in this particular format? Can't you use proper *serialisation*, e.g. JSON? – deceze Sep 07 '16 at 08: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 Sep 07 '16 at 08:13
  • Okay, fair enough, let's take that at face value. – deceze Sep 07 '16 at 08:17

4 Answers4

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
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

Dave
  • 3,073
  • 7
  • 20
  • 33
-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;
Poiz
  • 7,611
  • 2
  • 15
  • 17
-2

its work for you

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

echo $string;