timtj
timtj

Reputation: 94

PHP Mass String Replace

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?

Upvotes: 0

Views: 675

Answers (1)

AlexP
AlexP

Reputation: 9857

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));

Upvotes: 2

Related Questions