Is str_replace fast with an array?

My question is that using an array on str_replace is faster than doing it a few times. My question concerns only two replacements.

With an array

$phrase = "You should eat fruits, vegetables, and fiber every day."; $healthy = array("fruits", "vegetables"); $yummy = array("pizza", "beer"); $newphrase = str_replace($healthy, $yummy, $phrase); 

every word search times

 $phrase = "You should eat fruits, vegetables, and fiber every day."; $newphrase = str_replace("fruits", "pizza", $phrase); $newphrase = str_replace("vegetables", "beer", $phrase); 
+4
source share
3 answers

From PHP Docs to str_replace :

 // Outputs F because A is replaced with B, then B is replaced with C, and so on... // Finally E is replaced with F, because of left to right replacements. $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); $subject = 'A'; echo str_replace($search, $replace, $subject); // Outputs: apearpearle pear // For the same reason mentioned above $letters = array('a', 'p'); $fruit = array('apple', 'pear'); $text = 'a p'; $output = str_replace($letters, $fruit, $text); echo $output; 

Looking at these examples, PHP uses str_replace for each $search node array, so both of your examples are the same in terms of performance, however, you are sure that using the array to search and replace is more readable and future -prof, since you can easily change the array in future.

+1
source

I don’t know if this is faster, but I usually deal with the route of the array, because it is more convenient and readable ...

 $replace = array(); $replace['fruits'] = 'pizza'; $replace['vegetables'] = 'beer'; $new_str = str_replace(array_keys($replace), array_values($replace), $old_str); 

If I had to guess, I would say that making multiple calls to str_replace would be slower, but I'm not sure about the internal components of str_replace. With such things, I tended to go with readability / maintainability, since there are simply no benefits for optimization, since you can only get 0.0005 seconds of difference depending on # replacements.

If you really want to know the time difference, it will be practically impossible without creating a hugh dataset to get to the point where you can see the actual time difference and anomalies from the test confusion.

Using something like this ...

 $start = microtime(true); // Your Code To Benchmark echo (microtime(true) - $start) . "Seconds" 

... will allow you to request time.

0
source

Try using this before and after every other method, and you will soon see if there is a difference in speed:

 echo microtime() 
-1
source

All Articles