How can I add GET variables to end of the current url in php?
The simple way to it is:
$params = array_merge( $_GET, array( 'test' => 'testvalue' ) );
$new_query_string = http_build_query( $params );
This doesn't guarantee that test
will be at the end. If for some odd reason you need that, you can just do:
$params = $_GET;
unset( $params['test'] );
$params['test'] = 'testvalue';
$new_query_string = http_build_query( $params );
Note, however, that PHP query string parameter parsing may have some interoperability problems with other applications. In particular, PHP doesn't accept multiple values for any parameter unless it has an array-like name.
Then you can just forward to
( empty( $_SERVER['HTTPS'] ) ? 'http://' : 'https://' ) .
( empty( $_SERVER['HTTP_HOST'] ) ? $defaultHost : $_SERVER['HTTP_HOST'] ) .
$_SERVER['REQUEST_URI'] . '?' . $new_query_string
I created this simple PHP function based on Artefacto's Answer.
function addOrUpdateUrlParam($name, $value)
{
$params = $_GET;
unset($params[$name]);
$params[$name] = $value;
return basename($_SERVER['PHP_SELF']).'?'.http_build_query($params);
}
- It updates the value if you are changing a existing parameter.
- Adds up if it is a new value