Home » Php » How to convert an array to a string in PHP?

How to convert an array to a string in PHP?

Posted by: admin April 23, 2020 Leave a comment

Questions:

For an array like the one below; what would be the best way to get the array values and store them as a comma-separated string?

Array ( [0] => 33160,
        [1] => 33280,
        [2] => 33180,
        [3] => 33163,
        [4] => 33181,
        [5] => 33164,
        [6] => 33162,
        [7] => 33179,
        [8] => 33154,
        [9] => 33008,
        [10] => 33009,
        [11] => 33161,
        [12] => 33261,
        [13] => 33269,
        [14] => 33169,
        [15] => 33022,
        [16] => 33141,
        [17] => 33168,
        [18] => 33020,
        [19] => 33023,
        [20] => 33019,
        [21] => 33153,
        [22] => 33238,
        [23] => 33138,
        [24] => 33167,
        [25] => 33082,) 
How to&Answers:

I would turn it into CSV form, like so:

$string_version = implode(',', $original_array)

You can turn it back by doing:

$destination_array = explode(',', $string_version)

Answer:

I would turn it into a json object, with the added benefit of keeping the keys if you are using an associative array:

 $stringRepresentation= json_encode($arr);

Answer:

Using implode(), you can turn the array into a string.

$str = implode(',', $array); // 33160,33280,33180,...

Answer:

serialize() and unserialize() convert between php objects and a string representation.

Answer:

PHP has a built-in function implode to assign array values to string.
Use it like this:

$str = implode(",", $array);

Answer:

implode?

Answer:

implode(' ',$array);

Answer:

implode is function , which used in php for converting the array into string.

you may use like this

$string_product = implode(‘,’,$array)