Blogs

Blogs

Array to String with Comma

array to string

Mostly, User need to convert array to string with comma. user can add comma easily with any technology like c++, PHP, Javascript, etc.
here,we are taking an example with PHP.

$empName = array("Amit", "Viral", "Sahil", "Shruti", "Mahi", "Yuvi");
foreach ($empName as $value) {
echo $value.", ";                                                          
}   

and Output :

Amit, Viral, Sahil, Shruti, Mahi, Yuvi,

Here, Output is getting but no require last comma with last value. So, We need to remove it.
It’s see,

Last Comma Remove from string with PHP

$empName = array("Amit", "Viral", "Sahil", "Shruti", "Mahi", "Yuvi");
foreach ($empName as $key => $value) {
$prev = $empName[$key-1];                                                                
if(!empty($prev))
{
   echo ", ";
}
echo $value;                                                          
}   

Now you will get perfect Output :

Amit, Viral, Sahil, Shruti, Mahi, Yuvi

you can do same things with Jquery / Javascript.
It’s See Example,

Last Comma Remove from string with Jquery / Javascript

var empName = ["Amit", "Viral", "Sahil", "Shruti", "Mahi", "Yuvi"];
var employeeval ="";
$.each(empName,function(k,v){
  if(v != null){
     var prev = empName[k-1];
     if(prev != null){
       employeeval += ", ";
     }
     employeeval += v;  
  }
});
console.log(employeeval);