Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array to a string in PHP?

Tags:

arrays

php

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,)  
like image 860
shaytac Avatar asked Nov 23 '10 20:11

shaytac


People also ask

What is the name of function used to convert an array into a string?

By using the implode() function, we can convert all array elements into a string. This function returns the string.

How can I convert to string in PHP?

Answer: Use the strval() Function You can simply use type casting or the strval() function to convert an integer to a string in PHP.

What is implode function in PHP?

The implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of implode() is optional.


2 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) 
like image 136
Teekin Avatar answered Oct 14 '22 16:10

Teekin


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); 
like image 38
pixeline Avatar answered Oct 14 '22 17:10

pixeline