I try to avoid using loops in such situations. You should use implode () to combine lists with a common separator and use array_map () to handle any processing in this array before combining. Pay attention to the following implementations, which should express the universality of these functions. An array map can take a string (function name) representing either a built-in function or a user-defined function (first 3 examples). You can pass it a function using create_function () or pass a lambda / anonymous function as the first parameter.
$a = array(1, 2, 3, 4, 5); // Using the user defined function function fn ($n) { return $n * $n; } printf('[%s]', implode(', ', array_map('fn', $a))); // Outputs: [1, 4, 9, 16, 25] // Using built in htmlentities (passing additional parameter printf('[%s]', implode(', ', array_map( 'intval' , $a))); // Outputs: [1, 2, 3, 4, 5] // Using built in htmlentities (passing additional parameter $b = array('"php"', '"&<>'); printf('[%s]', implode(', ', array_map( 'htmlentities' , $b, array_fill(0 , count($b) , ENT_QUOTES) ))); // Outputs: ["php", "&<>] // Using create_function <PHP 5 printf('[%s]', implode(', ', array_map(create_function('$n', 'return $n + $n;'), $a))); // Outputs: [2, 4, 6, 8, 10] // Using a lambda function (PHP 5.3.0+) printf('[%s]', implode(', ', array_map(function($n) { return $n; }, $a))); // Outputs: [1, 2, 3, 4, 5]