For those who want a solution that supports the current parameters, updates if a new value is set, and adds new parameters, this performs the task:
The code
$domainurl='https://' . $_SERVER['SERVER_NAME']; $currenturl=$domainurl . $_SERVER['PHP_SELF']; function urlVars($new=array()) { $url=$GLOBALS['currenturl']; $vars=array_merge($_GET, $new); foreach ($vars as $key => $var) { $params[$x]='&' . $key . '=' . $var; $x++; } $str='?' . trim(implode($params), '&'); return $url .= $str; }
Usage example:
<a href="' . urlVars(array('page'=>'2', 'view'=>'30', etc.)) . '">Go To Page 2 & Show 30 Results</a>
Using the variable $currenturl
, which returns only the domain and path to the current page, not $ _SERVER ['REQUEST_URI'], which returns a query string, also solves the problem of repeated queries and allows you to change previously set parameters.
This is because array_merge()
will hold two or more arrays together, and if there are several keys with the same name, the last one declared takes the cake, and all the rest will be canceled. And since the $_GET
array is filled with the old parameters, it must arrive before the $new
array. Example:
$_GET['page']='1'; if ($new['page']='1') {array_merge($_GET, $new);} // 'page'=>'1' elseif ($new['page']='4') {array_merge($_GET, $new);} // 'page'=>'4' $_GET['page']='4'; if ($new['page']='2') {array_merge($_GET, $new);} // 'page'=>'2'
Note
The elegant function of this function and the whole reason I worked with it for several hours until it was perfect is that you do not need to specify the same parameters every time you have a new link / form or have some something is a shutdown array in another script that contains possible parameter keys. All that you put in the $new
array are parameters that are new (obviously) or are changing. It is universal!
source share