How to change array to string in PHP
Last Updated on Dec 13, 2022 - Written By Torikul Islam
You can convert an array to string using implode() function. It is a PHP built-in function.
Now we are going to convert the array elements into string from an example array. In this article, we are using two methods to convert array to string.
The implode() method is an alias for PHP join() function, which works exactly same as that of join() function.
Syntax:
string implode(‘separator’, ‘array’)
We need to provide two parameters.
1. Separator is the first parameter.
2. In second parameter, you need to place your array.
In the placement of parameters, you can use PHP variables.
Examples of converting array to string using PHP
<?php
// Declare an array
$array = array("Hello","world!", "Welcome", "to", "our","programming","world.");
// Converting array elements to string
$string = implode(" ",$array);
//showing output
echo $string;
?>
Or even
<?php
// Declare an array
$array = array( 0 =>"Hello", 1 =>"world!", 2 =>"Welcome", 3 =>"to", 4 =>"our", 5 =>"programming", 6 =>"world.");
// Converting array elements to string
$string = implode(" ",$array);
//showing output
echo $string;
?>
Output:
Hello world! Welcome to programming world.
Example 2: Use comma after each value
<?php
// Declare an array
$array = array("Hello","world!", "Welcome", "to", "our","programming","world.");
// Converting array elements to string
$string = implode(", ",$array);
//showing output
echo $string;
?>
Output:
Hello, world!, Welcome, to, our, programming, world.
You can also use join() function to convert array to string. To do this, you just need to use join() function instead implode() function.
Example 3: Use join function to get string from array
<?php
// Declare an array
$array = array("Hello","world!", "Welcome", "to", "our","programming","world.");
// Converting array elements to string
$string = join(", ",$array);
//showing output
echo $string;
?>
Output:
Hello, world!, Welcome, to, our, programming, world.
Similarly, if you want to convert your string to array, you need to use explode() in-build PHP function.