Convert PHP Array to String

We often need to convert a PHP array to a string. This code explains how to convert an array to 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

implode(separator,array); 

Example

<?php  
//assigning value to the array  
$arr = array("Hello","students", " ", "how","are","you");  
  
echo implode(" ",$arr);// Use of implode function  
?>

In the above example, an array variable is declared and assigned some values at the first line.

The implode() function will convert the array into a string in the following line. Two parameters are passed in the implode() function. The first is the separator, and the other one is the 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 an array of elements. We can pass three arguments in it. The first is for the separator, the second for array_name, and the last for the limit.

Syntax

explode(separator,array,limit); 

Example

<?php  
$str="Hello Students, How are you";  
  
//explode function breaks an string into array  
$arr=explode(" ",$str);  
  
print_r($arr);  
?> 

In the above example, a string variable is assigned some value. Then, explode() function breaks this string into an array. After this, we used the print_r() function, which prints all the array elements and their indexes.

Output

explode function

Using json() Function

In PHP, objects can be converted into JSON String 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

json_encode(obj_name); 

Example

<?php  
  
//Assigning values to the object variable  
@$myObj->name="Tarun";  
@$myObj->age=20;  
@$myObj->cidy=""Noida";  
  
//json_encode() put data into associative array with index  
  
$myJSON=json_encode($myObj);  
  
echo($myJSON);  
  
?>

In the above example, we assign the value to the object variable, and then, in json_encode(), we convert the matter to the array variable and make the associative array. 

Output

json_encode function


Similar Articles