Hezerac
Hezerac

Reputation: 334

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;

Upvotes: 1

Views: 1146

Answers (2)

vicentimartins
vicentimartins

Reputation: 46

An other form to your snippet...

    <?php
       $arr = array('first', 'second', 'third');
       foreach ($arr as $item) {
           $na[] = str_replace($item, '?', $item);
       }
       echo implode(', ', $na);

Hope help you!

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

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.

Upvotes: 2

Related Questions