I want to add GET parameters to URLs that may and may not contain GET parameters without repeating ?
or &
.
Example:
If I want to add category=action
$url="http://www.acme.com";
// will add ?category=action at the end
$url="http://www.acme.com/movies?sort=popular";
// will add &category=action at the end
If you notice I'm trying to not repeat the question mark if it's found.
The URL is just a string.
What is a reliable way to append a specific GET parameter?
Basic method
More advanced
You should put this in a function at least, if not a class.
I think you should do it something like this.
Here's a shorter version of the accepted answer:
Edit: as discussed in the accepted answer, this is flawed in that it doesn't check to see if
category
already exists. A better solution would be to treat the$_GET
for what it is - an array - and use functions likein_array()
.