I would prefer to use method 1 as its cleaner and more organised also Method 1 gives opportunity to use pairs from other source eg: bad words table in database. Method 2 would require another loop of sort..
<?php
$time_start = microtime(true);
for($i=0;$i<=1000000;$i++){
// Method 1
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$phrase = str_replace($healthy, $yummy, $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 1 in ($time seconds)\n<br />";
$time_start = microtime(true);
for($i=0;$i<=1000000;$i++){
// Method2
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$phrase = str_replace("fruits", "pizza", $phrase);
$phrase = str_replace("vegetables", "beer", $phrase);
$phrase = str_replace("fiber", "ice cream", $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 2 in ($time seconds)\n";
?>
Did Test 1 in (3.6321988105774 seconds)
Did Test 2 in (2.8234610557556 seconds)
Edit: On further test string repeated to 50k, less iterations and advice from ajreal, the difference is so miniscule.
<?php
$phrase = str_repeat("You should eat fruits, vegetables, and fiber every day.",50000);
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$time_start = microtime(true);
for($i=0;$i<=10;$i++){
// Method 1
$phrase = str_replace($healthy, $yummy, $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 1 in ($time seconds)\n<br />";
$time_start = microtime(true);
for($i=0;$i<=10;$i++){
// Method2
$phrase = str_replace("fruits", "pizza", $phrase);
$phrase = str_replace("vegetables", "beer", $phrase);
$phrase = str_replace("fiber", "ice cream", $phrase);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did Test 2 in ($time seconds)\n";
?>
Did Test 1 in (1.1450328826904 seconds)
Did Test 2 in (1.3119208812714 seconds)