note 94985 deleted from reserved.variables.request by crell
| From: | crell@php.net | Date: | Mon, 04 Apr 2022 16:54:10 +0000 |
| Subject: | note 94985 deleted from reserved.variables.request by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218113@lists.php.net to get a copy of this message | ||
Note Submitter: John Galt
----
I wrote a function because I found it inconvenient if I needed to change a particular parameter
(get) while preserving the others. For example, I want to make a hyperlink on a web page with the
URL http://www.example.com/script.php?id=1&blah=blah+blah&page=1
and change the value of "page" to 2 without getting rid of the other parameters.
<?php
function add_or_change_parameter($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);
}
?>
Now, I can add a hyperlink to the page
(http://www.example.com/script.php?id=1&blah=blah+blah&page=1) like this:
<a href="<?php echo add_or_change_parameter("page", "2");
?>">Click to go to page 2</a>
The above code will output
<a href="?id=1&blah=blah+blah&page=2">Click to go to page
2</a>
Also, if I was setting "page" to a string rather than just "2", the value would
be urlencode()'d.
<a href="<?php echo add_or_change_parameter("page", "banana+split!");
?>">Click to go to page banana split!</a>
would become
<a href="?id=1&blah=blah+blah&page=banana+split%21">Click to go to
page banana split!</a>
[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (theogony AT gmail DOT com), which
adds missing
echo instructions to the HREF tags.]