title: PHP Query String Manipulation
body: <p>I have a small issue with manipulating the current URL query string to add an extra parameter at the end.</p>
  
  <p>Per example, say there's a category layout for products, the URL would be:</p>
  
  <pre><code>index.php?category=3&amp;type=5
  </code></pre>
  
  <p>Now, on that page I have a link for a layout that is either a table or a grid. In those URLs I currently have:</p>
  
  <pre><code>&lt;a href="index.php?&lt;?php echo preg_replace($array,'',$_SERVER['QUERY_STRING']); ?&gt;&amp;layout=grid" ...
  </code></pre>
  
  <p>Then, I do the same for the table <code>href</code> as well. Also in my array I have just:</p>
  
  <pre><code>$array = array ( '/&amp;layout=table/', '/&amp;layout=grid/' )
  </code></pre>
  
  <p>Is this the right way, or is there a better way for doing this? I'm asking because without <code>preg_replace</code>, it will continue adding that same <code>layout</code> parameter everytime it is clicked, so it will also show the previous parameter, then the next, then the next.. without removing the previous <code>layout</code> parameters. </p>
  
  <p>Any insight on this will be much appreciated.</p>
  
  <p>EDIT: 
  Thanks to the answers below, I have created a little function:</p>
  
  <pre><code>function buildQuery($key,$value) {
  $params = $_GET;
  $params[$key] = $value;
  
  return http_build_query($params);
  }
  </code></pre>
  
  <p>Then its only a matter off:</p>
  
  <pre><code>&lt;a href="index.php?&lt;?php echo buildQuery('layout','grid'); ?&gt;"&gt;grid&lt;/a&gt;
  </code></pre>
  
  <p>this might seem pointless but i like to have my view / template files without the extra set vars. Im a clean freak. I might even return the 'index.php?' with it just so i can be more lazy, anyways something to play with now :)..</p>