0

I need to convert array to a string with square brackets and all.

This is the array

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

The output I need is,

$contstring = "['a', 'b', 'c']" ;

A printed array.

Implode()  

or serialize() doesn't do the job. Please suggest me a way to achieve this. Thanks in advance.

6
  • 1
    PHP has this magical concatenation operator: $contentstring = "['" . implode("', '",$content) . "']"; Commented Jan 8, 2017 at 19:00
  • Why implode doesn't do the job? It is exactly what you need Commented Jan 8, 2017 at 19:00
  • Implode prints the values. But I need the string with square brackets. Commented Jan 8, 2017 at 19:05
  • @Mark thank you very much for the answer Commented Jan 8, 2017 at 19:13
  • What you need is json_encode Commented Jan 8, 2017 at 19:17

2 Answers 2

1

implode() joins elements in array. basically :

$a = ['m','e','m','o'];
$str = implode($a,'');
echo $str;
// or : echo implode($a,'');

or make your own loop :

$str = '';
foreach($a as $c){
    $str .= $c;
}
echo $str;
Sign up to request clarification or add additional context in comments.

Comments

0

To get exactly what you want you just need to use implode with ', ' as your glue:

$content =['a', 'b', 'c'] ;
$contstring = "['" . implode($content, "', '") . "']" ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.