1

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;
2
  • 1
    This question is more suited for Code Review than Stack Overflow. Commented Oct 3, 2016 at 14:53
  • Isn't the code a bit pointless? I mean it always replaces all of the array elements with "?", because you are passing $arr[$i] as both the needle and input string. Commented Oct 3, 2016 at 14:53

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.