in this post, We’ll convert the array elements into a string. We are going to convert the array to string using three methods.
Array to String in PHP
Let’s convert array elements to string using PHP 7. We’ll discuss implode()
, json_encode()
and join()
method and create sample example to convert array to string.
Convert Array to String Using implode()
The implode()
method is a PHP built-in function for joining the items of an array. We just need to pass two parameters, One is an array of strings and the second is a delimiter (string to be used between the pieces) of your response string.
The delimiter is used to join them together into one string.
Syntax:
implode (separator, array)
Let’s take a simple example –
$blog_arr = Array ("Hi,","I","am","phpflow","blog."); $str = implode(" ",$blog_arr); echo $str;
Output:
Hi, I am phpflow blog.
PHP Array to String Using json_encode()
The json_encode()
function is a PHP inbuilt function that converts a PHP array or object to a JSON representation.
Syntax:
string json_encode( $value, $option, $depth )
The sample example:
$blog_arr = Array ("Hi,","I","am","phpflow","blog."); $str = json_encode($blog_arr); echo $str;
Output:
Hi, I am phpflow blog.
Array to String Using join()
The join()
method is a PHP built-in function that connects an array of elements separated by a string.
Syntax:
string join( $separator, $array)
The sample example:
$blog_arr = Array ("Hi,","I","am","phpflow","blog."); $str = join(" ", $blog_arr); echo $str;
Output:
Hi, I am phpflow blog.