Convert PHP Array to String

This code explains how to convert an array into a string in PHP using implode function.

There are two ways to convert an array into a string in PHP.
  1. Using implode() function
  2. Using json_encode() function

Using implode() Function

 
By using the implode() function, we can convert all array elements into a string. This function returns the string. The separator parameter in implode() function is optional. But it is good to use two arguments. 
 
Syntax
  1. implode(separator,array);  
Example
  1. <?php  
  2. //assigning value to the array  
  3. $arr = array("Hello","students"" ""how","are","you");  
  4.   
  5. echo implode(" ",$arr);// Use of implode function  
  6. ?>  
In the above example, at first line, an array variable is declared and assigned some values.
 
In the next line, the implode() function will convert the array into a string. Two parameters are passed in the implode() function. First is the separator and the other one is array_name.
 
Output
 
Implode Function
You can also convert that string into an array if required. For that, we can use PHP's explode() function.
 

explode() function

 
By using explode() function, we can convert a string into array elements. We can pass three arguments in it. The first one is for separator, second for array_name, and the last one for the limit.
 
Syntax
  1. explode(separator,array,limit);  
Example 
  1. <?php  
  2. $str="Hello Students, How are you";  
  3.   
  4. //explode function breaks an string into array  
  5. $arr=explode(" ",$str);  
  6.   
  7. print_r($arr);  
  8. ?>  
In the above example, a string variable is assigned some value. Then, explode() function breaks this string into an array. After this, we used print_r() function which prints all the array elements and its indexes.
 
Output
 
explode function

Using json() Function

 
In PHP, objects can be converted into JSON String by using the PHP function json_encode().
 
A common use of JSON is to read data from a web server and display the data on a web page.
 
Syntax
  1. json_encode(obj_name);  
Example
  1. <?php  
  2.   
  3. //Assigning values to the object variable  
  4. @$myObj->name="Tarun";  
  5. @$myObj->age=20;  
  6. @$myObj->cidy=""Noida";  
  7.   
  8. //json_encode() put data into associative array with index  
  9.   
  10. $myJSON=json_encode($myObj);  
  11.   
  12. echo($myJSON);  
  13.   
  14. ?>  
In the above example, we assigned the value to the object variable and then in json_encode()converts the value to the array variable and makes the associative array. 
 
Output
 
json_encode function