Friday, September 5, 2025
HomeLanguagesHow to create a string by joining the array elements using PHP...

How to create a string by joining the array elements using PHP ?

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
// PHP program to create a string by 
// joining the values of an array
  
// Function to get the string 
function get_string ($arr) {
      
    // Using implode() function to
    // join without separator 
    echo implode($arr); 
        
    // Using implode() function to
    // join with separator 
    echo implode("-", $arr); 
}
  
// Given array
$arr = array('Geeks','for','Geeks',"\n");
  
// function calling
$str = get_string ($arr); 
?>


Output

neveropen
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
// PHP program to create a string by 
// joining the values of an array
  
// Function to get the string 
function get_string ($arr){
      
    // Using join() function to
    // join without separator 
    echo join($arr); 
        
    // Using join() function to
    // Join with separator 
    echo join("-", $arr); 
}
  
// Given array
$arr = array('Geeks','for','Geeks',"\n");
  
// function calling
$str = get_string ($arr); 
?>


Output

neveropen
Geeks-for-Geeks-
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS