Forum Moderators: coopster
am I missing something, or is there really no built in function that performs the reverse of parse_str? You can parse a string to extract variables in the manner that $_GET extracts the variables from the URL query string...
...but why does there appear to be no reverse procedure? If you're managing webpage with PHP and there are mutliple variables in the URL, it's handy to have an easy way to generate the URL for links, etc.
I'm really surprised no such function exists. I had to write one by hand - and that only works for simple variables, not arrays. Function as below, assuming $args is an array like $_GET.
function make_url ($args)
{
$temp = array();
foreach ($args as $key => $value)
{
$temp[] = $key."=".$value;
}
$url = $_SERVER["PHP_SELF"] . "?" . implode("&", $temp);
return $url;
}
Michael
i never thought about it, thanks for your posting. i haven't researched yet if there is a function already for this, but in yours, don't forget to urlencode the variables in the query string:
$temp[] = $key."=".urlencode($value);
- hakre.
str = '';
foreach ($args as $key => $value)
{
$str .= (strlen($str) < 1)? "?" : "&";
$str .= $key . '=' . rawurlencode($value);
}
then just append that to the end of PHP_SELF.
With regard to the urlencode stuff, I assume I never need that if I know that values are always going to be integer numbers?
Michael
With regard to the urlencode stuff, I assume I never need that if I know that values are always going to be integer numbers?
if you know for shure the values are going to be integer (or only contain chars with no need to be escaped), then you don't need to urlencode. but for a robust function, it's ever good to have it in.
vars in php can be very tricky, because they are not bound to any type, they can be a number (int) or a string the same time, urlencode will make the function save for any case.
yeah to make it 100% perfect you should even check if its a number or a string because arrays won't work here anyway.
so the only left question is, how to handle arrays in that function ;).
- hakre.
Michael