How to create a string by joining the array elements using PHP ?
Last Updated :
01 Jun, 2020
We have given an array containing some array elements and the task is to join all the array elements to make a string. In order to do this task, we have the following methods in PHP:
Method 1: Using implode() Method : The implode() method is used to join an array of elements that are separated by a string. Joining can be done with or without separator.
Syntax :
string implode($separator, $array)
Example :
PHP
<?php
function get_string ($arr) {
echo implode($arr);
echo implode("-", $arr);
}
$arr = array('Geeks','for','Geeks',"\n");
$str = get_string ($arr);
?>
Output
GeeksforGeeks
Geeks-for-Geeks-
Method 2: Using join() Method : The join() method is used to join an array of elements that are separated by a string. Joining can be done with or without separator. The join() method is same as the implode() method.
Syntax :
string join($separator, $array)
Example :
PHP
<?php
function get_string ($arr){
echo join($arr);
echo join("-", $arr);
}
$arr = array('Geeks','for','Geeks',"\n");
$str = get_string ($arr);
?>
Output
GeeksforGeeks
Geeks-for-Geeks-
Like Article
Suggest improvement
Share your thoughts in the comments
Add Your Comment
Please Login to comment...