keeping url parameters during pagination

If you wanted to write your own function that did something like http_build_query, or if you needed to customize it's operations for some reason or another:

<?php 
function add_edit_gets($parameter, $value) { 
    $params = array(); 
    $output = "?"; 
    $firstRun = true; 
    foreach($_GET as $key=>$val) { 
        if($key != $parameter) { 
            if(!$firstRun) { 
                $output .= "&"; 
            } else { 
                $firstRun = false; 
            } 
            $output .= $key."=".urlencode($val); 
         } 
    } 

    if(!$firstRun) 
        $output .= "&"; 
    $output .= $parameter."=".urlencode($value); 
    return htmlentities($output); 
} 

?>

Then you could just write out your links like:

<a href="<?php echo add_edit_gets("page", "2"); ?>">Click to go to page 2</a>

You could use http_build_query() for this. It's much cleaner than deleting the old parameter by hand.

It should be possible to pass a merged array consisting of $_GET and your new values, and get a clean URL.

$new_data = array("currentpage" => "mypage.html");
$full_data = array_merge($_GET, $new_data);  // New data will overwrite old entry
$url = http_build_query($full_data);

In short, you just parse the URL and then you add the parameter at the end or replace it if it already exists.

$parts = parse_url($url) + array('query' => array());
parse_str($parts['query'], $query);
$query['page'] = $page;
$parts['query'] = http_build_str($query);
$newUrl = http_build_url($parts);

This example code requires the PHP HTTP module for http_build_url and http_build_str. The later can be replaced with http_build_query and for the first one a PHP userspace implementation exists in case you don't have the module installed.

Another alternative is to use the Net_URL2 package which offers an interface to diverse URL operations:

$op = new Net_URL2($url);
$op->setQueryVariable('page', $page);
$newUrl = (string) $op;

It's more flexible and expressive.