title: Add/Replace URL GET parameter depending on current URL
body: <p>I’ve tried for some time now to solve what probably is a small issue but I just can’t seem get my head around it. I’ve tried some different approaches, some found at SO but none has worked yet.</p>
  
  <p>The problem consists of this:<br>
  I’ve a show-room page where I show some cloth. On each single item of cloth there is four “views”  </p>
  
  <ol>
  <li><strong>Male</strong></li>
  <li><strong>Female</strong></li>
  <li><strong>Front</strong></li>
  <li><strong>Back</strong></li>
  </ol>
  
  <p>Now, the users can filter this by either viewing the <strong>male</strong> or <strong>female</strong> model but they can also filter by viewing <strong>front</strong> or <strong>back</strong> of both gender.</p>
  
  <p>I’ve created my script so it detects the URL query and display the correct data but my problem is to “build” the URL correctly.</p>
  
  <p>When firstly enter the page, the four links is like this:</p>
  
  <ol>
  <li><strong>example.com?gender=male</strong></li>
  <li><strong>example.com?gender=female</strong></li>
  <li><strong>example.com?site=front</strong></li>
  <li><strong>example.com?site=back</strong>  </li>
  </ol>
  
  <p>This work because it’s the “default” view (the default view is set to gender=male &amp;&amp; site=front) in the model.</p>
  
  <p>But if I choose to view <strong>?gender=female</strong> the users should be able to filter it once more by adding <strong>&amp;site=back</strong> so the complete URL would be: example.com?gender=female&amp;site=back</p>
  
  <p>And if I then press the link to see <strong>gender=male</strong> it should still keep the URL parameter <strong>&amp;site=back</strong>.</p>
  
  <p>What I’ve achived so far is to append the parameters to the existing URL but this result in URL strings like: <strong>example.com?gender=male&amp;site=front&amp;gender=female</strong> and so on…</p>
  
  <p>I’ve tried but to use the <strong>parse_url</strong> function, the <strong>http_build_query($parms)</strong> method and to make my “own” function that checks for existing parameters but it does not work.</p>
  
  <p>My latest try was this:  </p>
  
  <pre><code>_setURL(‘http://example.com?gender=male’, ‘site’, ‘back’);
  function _setURL($url, $key, $value) {
      $separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&amp;';
  
      $query = $key."=".$value;
      $url .= $separator . $query;
      var_dump($url); exit;
  }
  </code></pre>
  
  <p>This function works unless the $_GET parameter already exists and thus should be replaced and not added.</p>
  
  <p>I’m not sure if there is some “best practice” to solve this and as I said I’ve looked at a lot of answers on SO but none which was spot on my issue.  </p>
  
  <p>I hope I’ve explained myself otherwise please let me know and I’ll elaborate.<br>
  Any help or advice would be appreciated</p>