views:

132

answers:

2

I'm building a set of pages where I have a number of GET variables and it is often valuable to keep passing it along to the next page. This leads to ugly code where I have to have "if this $_GET variable is set, dynamically add it to this hyperlink". This is, in many senses, not a problem; but I had the thought "there must be a better way to do this", I mean after all basically all I want is to take the '?' and everything after it and append it to the links on that page, it would seem this should be rather simple (or at least possible to do in a for loop). I tried google searching but couldn't find anything, so I figured I'd see if any of you happen to know.

Why not use SESSION? Because these pages need to be capable of being bookmarked.

Thank you.

+3  A: 

A quick idea would be to :

  • use parse_url to extract the parameters from the current URL to an array
    • or directly use $_GET, which already contains those parameters
  • use array_merge, to merge :
    • The list of existing parameters (see previous point)
    • The list of new parameters
  • use http_build_query to build the new query-string
    • Notice you might have to specify the third parameter : by default, it will be equal to & -- which is not always what you need, depending on the kind of output you are generating


And, once you have your new query-string, it's just matter of concatenation :

  • The new URL, without any query string
  • The ? character
  • The new query-string

ANd here you are ;-)

Pascal MARTIN
+1, I removed my answer since your answer is a far better idea than mine. I couldn't agree more with your response.
Anthony Forloney
@Anthony Thanks :-)
Pascal MARTIN
When I saw the answer with foreach (now deleted), I felt stupid for asking (no idea why using foreach on $_GET never occurred to me). But because I asked I got to learn about http_build_query, so thank you for that.
aterimperator
`http_build_query` is great function ;; not known enough, I suppose ; but great nevertheless ;-) ;; you're welcome :-) Have fun !
Pascal MARTIN
I had deleted my response, but that was for `mod_rewrite` which isn't essentially *helping* the issue rather covering it up with prettier URL's :)
Anthony Forloney
+1  A: 

This variable contains the request parameters. You could pass these to each link on the pages.

eg: foo=test1&bar=test2

Prepend the ? and you are done.

$_SERVER['QUERY_STRING']
Jurgen H