Hezerac Hezerac - 1 year ago 92
PHP Question

php replace all strings in array, and output comma seperated string

Wrote a little snippet that replaces all strings in an array, and finally outputs them as a comma separated string (shown below).

It seems a bit much though for such simple functionality. So my question is can anyone come up with a more elegant way of writing this?

$arr = array('first', 'second', 'third');
$size = count($arr);
$newArr = array();

for($i=0; $i<$size; $i++) {

$newArr[$i] = str_replace($arr[$i], '?', $arr[$i]);


$final = implode(', ', $newArr);

echo $final;

Answer Source

str_replace() accepts arrays:

$newArr = str_replace($arr, '?', $arr);
$final = implode(', ', $newArr);

But I hope this was just an example as you are just replacing anything in the array with ? which is easier done.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download