title: Writing Elegant PHP Code: Cleaning Up Unnecessary Loops and Merging Arrays
body: <p>I'm pulling input from six (6) different textareas, exploding the array with \r\n as the delimiter, and looping through each set of data twice in order to replace it.</p>
  
  <p>For example, I have textarea inputs where people can put colors similar to the main one listed, so the input for the textarea titled 'Blue' might be <code>Aqua\r\nRoyal Blue\r\nTeal</code></p>
  
  <p>Then I have input boxes for Red, Orange, Yellow, Green, and Purple with similar data.</p>
  
  <p>I want to replace the user input -- in this example, Aqua -- with <code>&lt;span class="blue"&gt;Aqua&lt;/span&gt;</code>. Anything input in the blue box gets wrapped in the 'blue' class, anything from red in <code>class="red"</code>, etc.</p>
  
  <p>I've got this all working fine and well, cycling through each set of data twice: one foreach loop to find the text, another to create the replacement text, and then finally simply using preg_replace to actually perform it the substitution.</p>
  
  <pre><code>$find_blue     = explode ("\r\n", $blue);
  $replace_blue  = explode ("\r\n", $blue);
  
  $i = 0;
  foreach($replace_blue AS &amp;$html)
  {
    $find_blue[$i] = trim($find_blue[$i]);
    $html = '&lt;span class="blue"&gt;' . $find_blue[$i] . '&lt;/span&gt;';
    $i++;
  }
  foreach($find_blue AS &amp;$found)
  {
    $found = preg_quote(htmlspecialchars($found));
    $found = '~\b('.$found.')\b)~i';
  }
  
  $output = preg_replace($find_blue, $replace_blue, $output);
  </code></pre>
  
  <p>This works swimmingly well, but I think it's clumsy code having 12 loops (2x per color) all doing the same thing. I'd like to write cleaner, more efficient, <strong>better</strong> code, and I know array_merge exists, but I'm unsure how to integrate it or make everything coherent and cohesive.</p>