How to create comma separated list from an array in PHP?

PHPServer Side ProgrammingProgramming

To create a comma-separated list from an array in PHP, the code is as follows−

Example

 Live Demo

<?php
   $arr = array( " John ", "Jacob ", " Tom ", " Tim ");
   echo "Array with leading and trailing whitespaces...\n";
   foreach( $arr as $value ) {
      echo "Value = $value \n";
   }
   echo "\nComma separated list...\n";
   print_r(implode(', ', $arr));
   $result = array_map('trim', $arr);
   echo "\nUpdated Array...\n";
   foreach( $result as $value ) {
      echo "Value = $value \n";
   }
?>

Output

This will produce the following output−

Array with leading and trailing whitespaces...
Value = John
Value = Jacob
Value = Tom
Value = Tim
Comma separated list...
   John , Jacob , Tom , Tim
Updated Array...
Value = John
Value = Jacob
Value = Tom
Value = Tim

Example

Let us now see another example −

 Live Demo

<?php
   $arr = array(100, 200, 300, 400, 500);
   echo "Comma separated list...\n";
   print_r(implode(', ', $arr));
?>

Output

This will produce the following output−

Comma separated list... 
100, 200, 300, 400, 500
raja
Published on 26-Dec-2019 10:05:44
Advertisements