How to Create a String by Joining the Array Elements using PHP

admin_img Posted By Bajarangi soft , Posted On 03-12-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:

string joining to the array elements

Method 1: Using implode() MethodThe 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:

//joining the values of an array
//function  to get the string
function  get_string($arr){

//using implode ()function to join without seperator

echo implode($arr);


//using implode() function to join with seperator
echo implode("-",$arr);
}
//given array
$arr=array('company','website',"\n");

//function  calling

$str=get_string($arr);
?>

 

Method 2: Using join() MethodThe 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
//joining the values of an array
//function  to get the string
function  get_string($arr){

//using implode ()function to join without seperator

echo join($arr);


//using implode() function to join with seperator
echo join("-",$arr);
}
//given array
$arr=array('company','website',"\n");

//function  calling

$str=get_string($arr);
?>

Related Post