0

In PHP, I want to execute str_replace on multiple variables, efficiently, when all variables shall abide by the same str_replace values.

Bascially, I am expecting to see the following:

$var1=str_replace("0.00","\$0",$var1);
$var2=str_replace("0.00","\$0",$var2);
$var3=str_replace("0.00","\$0",$var3);
$var4=str_replace("0.00","\$0",$var4);
...

this is repetitive and especially annoying when adding more variables to such replace. I have constructed the following loop

foreach ( array("var1","var2","var3","var4") as $variablename ) {
${$variablename} = str_replace("0.00","\$0",${$variablename});
}

This loop works (for those of you viewing this page looking for such an example) , however, I am not convinced that this is the most efficient way (assuming mass replacing)

Any thoughts?

3
  • 2
    There would be a more efficient way if your list of numbered variables were an array instead. Commented Dec 29, 2013 at 3:11
  • 2
    ...Agree with @mario. If the variables are related as they appear to be by virtue of requiring the same set of operations, then they may belong in a data structure. Commented Dec 29, 2013 at 3:12
  • so str_replace("0.00","\$0",array("var1","var2",...)) as such? Commented Dec 29, 2013 at 3:13

1 Answer 1

2

The third parameter of str_replace can accept an array of variables to perform the replace on. It should be better performing that any custom loop.

$results = str_replace("0.00","\$0", array($var1, $var2, $var3));
Sign up to request clarification or add additional context in comments.

4 Comments

I was aware that both the first and second paramaters of this command accepted arrays, but I didn't remember reading about an array-applicable third parameter in the manual. I appreciate your answer. It looks cleaner than mine, and it makes sense too :)
As a note to others. This works, indeed. The $results variable is stored as an array, and in no way does the variable itself interfere with normal operations. When printing the array, print_r($results) it displays the values of $var1,$var2, and $var3, however the "keys" are numerical, and do not contain the original variable name.
@timtj: If you want to retain the variable names, then an uncommon workaround is creating the array via compact("var1", "var2", "var3"). You might even use extract(str_replace("from", "to", compact("var1", "var2"))); to keep/overwrite your original varlist.
It seems like a possible workaround. However, is it efficient or will it bog down after multiple variables?

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.