Quick Reach
PHP Array to String Conversion
In this chapter, we will explain how to use implode() function of PHP to convert an array to a string. Note that the Join() is an alias to implode() function.
The implode function Video
You may also watch a short video of this tutorial.
See implode example
- In certain scenarios, you might need to convert array values to string.
- You can convert an array to string by using implode() function of PHP.
- The implode() function places the separator (+ or some other special symbol) between each value of array element.
- The implode() basically joins array elements with a string.
An implode example with + separator
How to use implode function for array to string conversion?
This is how you may use the implode function of PHP for converting an array to string:
string implode ($separator,$array_name)
Note: If you don’t place a separator then PHP will not generate any error message.
An example of array to string by implode with comma
In the following example, a single dimensional array is created with three elements. After that, the implode function is used with that array for converting the array into the string. The comma is used as the separator. The end result is displayed by using the echo statement, have a look:
Experience this example online
1
2
3
4
5
6
7
8
9
|
<?php
$arr_implode = array(‘name’, ’email’, ‘phone’);
$separater = implode(“,”, $arr_implode);
echo $separater; // name,email,phone
?>
|
You saw the converted string is displayed with the array elements joined with a comma.
Using the + characters as separator example
Now, using the same array of three elements as in above example, however, this time I used the + character rather than a comma to join the array elements after conversion by implode function. See the code and output:
Experience this example online
1
2
3
4
5
|
$arr_implode = array(‘name’, ’email’, ‘phone’);
$separater = implode(“+”, $arr_implode);
echo $separater; // name,email,phone
|
You can see, the array elements are joined with the + character.
An example with two-dimensional array
In this example, an array of three elements is created. The array contains fruit names. After that, the implode PHP function is used for converting this array to string. Finally, the print_r function is used for displaying it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php
$arr_fruit=$array2=array(“Apples”,“Banana”,“strawberry”);
$arr_fruit=implode($arr_fruit,“,”);
print_r($arr_fruit);
print“<br/>”;
$arr_fruit=implode(“+”,$array2);
print_r($arr_fruit);
?>
|
Experience this example online
Output:
Apples,Banana,strawberry
Apples+Banana+strawberry
You should also read: PHP arrays | PHP split string (explode function)
Leave A Comment?